/*
* @(#)MaintDmsDocumentAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.dcivision.alert.bean.MtmUpdateAlertRecipient;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertSystemLog;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.dao.MtmUpdateAlertRecipientDAObject;
import com.dcivision.alert.dao.UpdateAlertDAObject;
import com.dcivision.alert.dao.UpdateAlertTypeDAObject;
import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.EmailAuditTrailConstant;
import com.dcivision.dms.bean.DmsDefaultProfileSetting;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.client.analyzer.DmsDocumentAnalyzer;
import com.dcivision.dms.core.DmsWinClientOperartionManager;
import com.dcivision.dms.core.DocumentEmailArchiveManager;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.core.EmptyContentException;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.dms.core.WebdavOperationManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsDocumentDetailDAObject;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.dms.dao.MtmDocumentRelationshipDAObject;
import com.dcivision.framework.ApplicationContainer;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.SysUserDefinedIndex;
import com.dcivision.framework.bean.SysUserDefinedIndexDetail;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.WorkflowActionFormInterface;
import com.dcivision.framework.web.WorkflowActionInterface;
import com.dcivision.mail.bean.EmailAttachmentImpl;
import com.dcivision.mail.bean.EmailMessageImpl;
import com.dcivision.mail.core.EmailReceiver;
import com.dcivision.mail.core.EmailReceiverFactory;
import com.dcivision.upload.core.MultipleFileUploadUtil;
import com.dcivision.workflow.WorkflowOperationConstant;
import com.dcivision.workflow.bean.WorkflowProgressAttachment;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.core.SystemWorkflowConstant;
import com.dcivision.workflow.core.WorkflowStepManager;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;

/**
  MaintDmsDocumentAction.java

  This class is for maint dms dmsDocument action

    @author          Zoe Shum
    @company         DCIVision Limited
    @creation date   06/08/2003
    @version         $Revision: 1.287.2.15 $
 */

public class MaintDmsDocumentAction extends com.dcivision.setup.web.AbstractMaintPermissionAction implements com.dcivision.framework.web.WorkflowActionInterface {

  public static final String REVISION = "$Revision: 1.287.2.15 $";

  protected static String MESSAGE_RECORD_MOVE = "dms.message.records_move";
  protected static String MESSAGE_RECORD_COPY = "dms.message.records_copy";
  protected static String MESSAGE_RECORD_RENAME = "dms.message.records_rename";

  protected static String scannedUDFName = "";
  protected static String CLIENT_TYPE_WORD = "";
  protected static String CLIENT_TYPE_OUTLOOK = "";
  protected String parentID = "";
  protected String rootID = "";
  protected String docType = "";
  protected DmsDocumentAnalyzer documentAnalyzer = null;

  private String odmaProcess = "";  
  
  
  
  public MaintDmsDocumentAction() {
    super();
  }
  

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  
  public String getMajorDAOClassName() {
    return("com.dcivision.dms.dao.DmsDocumentDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  
  public String getFunctionCode() {
    return(SystemFunctionConstant.DMS_PERSONAL_FOLDER);
  }

  /**
   * execute - Override the parent function.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
	  /*
	   * joan.xiong add code for bug EIP-172 by 2006/10/12
	   */
	  if(!Utility.isEmpty(request.getSession().getAttribute(org.apache.struts.Globals.MESSAGE_KEY))){
		  this.addMessage(request, (String)request.getSession().getAttribute(org.apache.struts.Globals.MESSAGE_KEY));
		  request.getSession().removeAttribute(org.apache.struts.Globals.MESSAGE_KEY);
	  }
	  if(!Utility.isEmpty(request.getSession().getAttribute(org.apache.struts.Globals.ERROR_KEY))){
		  this.addError(request, (String)request.getSession().getAttribute(org.apache.struts.Globals.ERROR_KEY));
		  request.getSession().removeAttribute(org.apache.struts.Globals.ERROR_KEY);
	  }
	  /*
	   * joan.xiong add code end
	   */
	  MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    
    //Operate for the before workflow infomation page display status.
    if(!Utility.isEmpty(request.getParameter("isShowWorkflowPage"))){
      request.setAttribute("isShowWorkflowPage", request.getParameter("isShowWorkflowPage"));
    }
    
    //if this is odma process    
    odmaProcess = request.getParameter("odmaProcess");  
    String notesProcess = request.getParameter("Notes");
    String clientType = request.getParameter("clientType"); 
    List resultInfo = new ArrayList();
    //if request form odma ,some field is store at xml,so parse xml field to form first    
    if ("odma".equals(odmaProcess)){      
      try {
        parseFormXmlDataToForm(actionForm);
      } catch (Exception e) {
        log.error(e, e);
      }
      
      // process client from outlook
      if(DmsWinClientOperartionManager.CLIENT_TYPE_MSOUTLOOK.equals(actionForm.getClientType())){
        this.insertMail(mapping,form,request,response);
        return mapping.findForward("DMS.ODMA_RESULT");
      }
  
    }
    
    //process client from Notes
    if("Notes".equals(notesProcess)){
      try{
      	parseFormZIPDataToForm(actionForm);
				this.insertMailNotesForPost(mapping, form, request, response);
    	  return mapping.findForward("DMS.ODMA_RESULT");
      }catch(Exception e){
        log.error(e, e);
      }
    }
    
   
    // Set function code if necessary.
    if (!Utility.isEmpty(actionForm.getCurFunctionCode())) {
      this.setFunctionCode(actionForm.getCurFunctionCode());
    }else if(!Utility.isEmpty(request.getParameter("sCurFunctionCode"))){
      this.setFunctionCode(request.getParameter("sCurFunctionCode"));
    }

    if( !Utility.isEmpty(functionCode)) {
      request.setAttribute(GlobalConstant.FUNCTION_CODE_KEY,functionCode);
    }
    
    String opMode = actionForm.getOpMode();
    String navMode = actionForm.getNavMode();    
    
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);

    //lee add for bug 6022 in 06/08/03 start....
    //if action from invitation, not check function code.
    Integer updateAlertID = TextUtility.parseIntegerObj(request.getParameter("updateAlertID"));
    Integer updateAlertSystemLogID = TextUtility.parseIntegerObj(request.getParameter("updateAlertSystemLogID"));
    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer,conn);
    Integer tmpUpdateAlertID = updateAlertDAO.getInvitationIDByAlertIDorSystemLogID(updateAlertID, updateAlertSystemLogID);
    boolean isInvitation = (tmpUpdateAlertID!=null);
    if (!isInvitation) {
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward!=null) {
        return forward;
      }
    }
    //lee add for bug 6022 in 06/08/03 end...

    // Retrieve the default document profile settings.
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    docRetrievalManager.checkNSetDefaultProfileList(request);

    // Get the location path.
    parentID = actionForm.getParentID();
    rootID = actionForm.getRootID();
    docType = actionForm.getDocumentType();
    request.setAttribute("documentID", actionForm.getID());

    /* Retrieval the document information for display in JSP */
    if (!DmsOperationConstant.DMS_CREATE_BY_UPLOAD.equals(actionForm.getCreateType()) ){
      // Retrieve the root folder document object.
      DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(TextUtility.parseIntegerObj(actionForm.getRootID()));
      //Check for null parentID rootID hanling
      if (Utility.isEmpty(parentID) || "null".equals(parentID) ||
          Utility.isEmpty(rootID) || "null".equals(rootID)) {
        DmsRoot personalRoot = rootRetrievalManager.getRootObjectByOwnerID(sessionContainer.getUserRecordID());
        documentRoot = docRetrievalManager.getRootFolderByRootID(personalRoot.getID());
        parentID = TextUtility.formatIntegerObj(documentRoot.getParentID());
        rootID = TextUtility.formatIntegerObj(personalRoot.getID());
        actionForm.setRootID(rootID);
        actionForm.setParentID(parentID);
      }
      request.setAttribute("rootFolder", documentRoot);

      String path = "";
      if (parentID != null) {
        path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(parentID));
      }
      request.setAttribute("location", path);

      if ( DmsOperationConstant.CREATE_EMPTY_FILE.equals(opMode) || DmsOperationConstant.DMS_RECORD_EMPTY.equals(actionForm.getRecordStatus()) ||
         DmsOperationConstant.MOVE_OPERATION.equals(opMode) || DmsOperationConstant.COPY_OPERATION.equals(opMode) ||
         (DmsOperationConstant.CREATE_EMPTY_FILE.equals(opMode) || GlobalConstant.NAV_MODE_EDIT.equals(navMode)) || 
         DmsOperationConstant.COPY_MORE_OPERATION.equals(opMode)
         ) {

        // Retrieve the accessible public root list.
        List publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
        request.setAttribute("publicRootList", publicRootList);
      }
    }
    //empty reference file insert and update operation
    if (DmsOperationConstant.CREATE_EMPTY_FILE.equals(opMode)) {
      this.init(mapping, actionForm, request, response);      
      if (GlobalConstant.NAV_MODE_EDIT.equals(navMode)) {
        this.selectRecord(mapping, actionForm, request, response);
      }else{
    	  actionForm.setClearIndex(false);
      	  this.getParentFolderDefaultProfile(mapping, actionForm, request, response);  
      }
      return mapping.findForward(DmsOperationConstant.CREATE_EMPTY_FILE);
    }
    
    //update operation of the reference file
    if ((GlobalConstant.OP_MODE_UPDATE.equals(opMode)) && (DmsOperationConstant.CREATE_EMPTY_FILE.equals(navMode))) {
    
      try {
        this.updateRecord(mapping, actionForm, request, response);
        this.handleWorkflowRoutine(mapping, actionForm, request, response, opMode, navMode);
        this.commit(request);
        addMessage(request, MESSAGE_RECORD_UPDATE);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        return mapping.findForward(DmsOperationConstant.CREATE_EMPTY_FILE);
      } else {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        return mapping.findForward(DmsOperationConstant.CREATE_EMPTY_FILE_VIEW);
      }
    }
    // end of update opeation of reference file


    if (GlobalConstant.OP_MODE_LIST_DELETE.equals(actionForm.getOpMode())) {
        try {
        	this.deleteRecord(mapping, actionForm, request, response);
        	this.commit(request);
        	actionForm.setOpMode(null);
//        	this.addMessage(request, DmsErrorConstant.MESSAGE_RECORD_DELETED_SUCCESS, actionForm.getID());
        } catch (ApplicationException e) {
        	this.rollback(request);
        	this.handleApplicationException(request, e);
        }
        return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
      }

    if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
      // Insert operation.
      log.debug("enter insert");
      try {
        // EIP-438 06/12/29 LEE / resolve the problem duplicate name
        this.regeditDuplicateNameCache(request);
        this.insertRecord(mapping, actionForm, request, response);
      log.debug("enter insert 2 ");
      try {
        this.handleWorkflowRoutine(mapping, actionForm, request, response, opMode, navMode);
      } catch (ApplicationException e) {
        log.error(e, e);
        throw e;
      }
      log.debug("enter insert 3 ");
        this.commit(request);
        addMessage(request, MESSAGE_RECORD_INSERT);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      } finally {
        // EIP-438 06/12/29 LEE / resolve the problem duplicate name
        this.unlockDuplicateNameCache(request);
      }
      if (GlobalConstant.NAV_MODE_FREEZE.equals(navMode)) {
        return null;
      } else {
        if (isError(request)) {
          // for odma return   
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","newDocument" );
            request.setAttribute("result","faild" );
            request.setAttribute("inforCode","ERROR_NEWDOC_01" );            
            request.setAttribute("documentID",actionForm.getID());
            return mapping.findForward("DMS.ODMA_RESULT");
          }else if("paraScan".equals(odmaProcess)){
            request.setAttribute("odmaGetType","newDocument" );
            request.setAttribute("result","faild" );
            request.setAttribute("inforCode","ERROR_NEWDOC_01" );            
            request.setAttribute("documentID",actionForm.getID());
            return mapping.findForward("DMS.ODMA_RESULT");            
          }else if ("TEST".equals(((MaintDmsDocumentForm)form).getReturnTo())){
            return mapping.findForward("DMS.MAINT.PARASCAN.V");
          }    
          else{
            actionForm.setNavMode(GlobalConstant.NAV_MODE_REFRESH);
            this.refreshFormData(mapping, actionForm, request, response);
            if (DmsOperationConstant.DMS_RECORD_EMPTY.equals(actionForm.getRecordStatus())) {
              actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
              return mapping.findForward(DmsOperationConstant.CREATE_EMPTY_FILE);
            } else {
              //lee.lv edit below for bug 5317 in 06/06/17
              if (DmsDocument.FOLDER_TYPE.equals(((MaintDmsDocumentForm)form).getDocumentType())){
                List docDetailsList = docRetrievalManager.retrievalDocumentDetailsList(request);
                if (docDetailsList!=null && docDetailsList.size() > 0){
                  actionForm.setDocumentDetails(docDetailsList);
                }
                actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
                return mapping.findForward("DMS.MAINT.FORDER");
              }else {
                actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
                return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
              }
            }
          }
        } else {
          // for odma return   
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","newDocument" );
            request.setAttribute("result","success" );
            request.setAttribute("inforCode","MESSAGE_NEWDOC_01" );            
            request.setAttribute("documentID",actionForm.getID());
            return mapping.findForward("DMS.ODMA_RESULT");
          }else if("paraScan".equals(odmaProcess)){
            request.setAttribute("odmaGetType","newDocument" );
            request.setAttribute("result","success" );
            request.setAttribute("inforCode","MESSAGE_NEWDOC_01" );            
            request.setAttribute("documentID",actionForm.getID());
            return mapping.findForward("DMS.ODMA_RESULT");
          } else{
            //===== For Handle The Second Step IS Dynamic Assign Owner Begin =======           
            HashMap tmp = (HashMap) request.getAttribute("assignStepMap");
            if (tmp!=null && !tmp.isEmpty()) {
              actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
              request.setAttribute("returnUrl","dms/ListDmsPublicDocument.do?parentID="+request.getParameter("parentID")+"&rootID="+request.getParameter("rootID"));
              return mapping.findForward(WorkflowOperationConstant.WORKFLOW_ASSIGN_USER);
            }  
            //===== For Handle The Second Step IS Dynamic Assign Owner End   ======= 
            actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
            if (DmsOperationConstant.DMS_RECORD_EMPTY.equals(actionForm.getRecordStatus())) {
              return mapping.findForward(DmsOperationConstant.CREATE_EMPTY_FILE_VIEW);
            }
            else if ("TEST".equals(((MaintDmsDocumentForm)form).getReturnTo())){
              return mapping.findForward("DMS.MAINT.PARASCAN.V");
            }            
             //if document type is folde ,then returnt to EditDmsDocumentFolder.jsp
            else if (!"SCAN".equals(((MaintDmsDocumentForm)form).getReturnTo())&&DmsDocument.FOLDER_TYPE.equals(((MaintDmsDocumentForm)form).getDocumentType())){
                return mapping.findForward("DMS.MAINT.FORDER");
            }
            else {
              return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
            }
          }  
        }
      }
    }   if (GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode)) {
        // Insert operation.
        log.debug("enter insert");
        try {
          // EIP-438 06/12/29 LEE / resolve the problem duplicate name
          this.regeditDuplicateNameCache(request);
          
          this.insertRecord(mapping, actionForm, request, response);
        log.debug("enter insert 2 ");
        try {
          this.handleWorkflowRoutine(mapping, actionForm, request, response, opMode, navMode);
        } catch (ApplicationException e) {
          this.rollback(request);  
          log.error(e, e);
          throw e;
        }
        log.debug("enter insert 3 ");
        //form.reset(mapping, request);        
        this.init(mapping, actionForm, request, response);
          this.commit(request);
          addMessage(request, MESSAGE_RECORD_INSERT);
        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        } finally {
          // EIP-438 06/12/29 LEE / resolve the problem duplicate name
          this.unlockDuplicateNameCache(request);
        }
        if (GlobalConstant.NAV_MODE_FREEZE.equals(navMode)) {
          return null;
        } else {
          if (isError(request)) {
            actionForm.setNavMode(GlobalConstant.NAV_MODE_REFRESH);
            this.refreshFormData(mapping, actionForm, request, response);
            if (DmsOperationConstant.DMS_RECORD_EMPTY.equals(actionForm.getRecordStatus())) {
              actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
              return mapping.findForward(DmsOperationConstant.CREATE_EMPTY_FILE);
            } else {
              actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
              return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
            }
          } else {
            //===== For Handle The Second Step IS Dynamic Assign Owner Begin =======           
            HashMap tmp = (HashMap) request.getAttribute("assignStepMap");
            if (tmp!=null && !tmp.isEmpty()) {
              actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);              
              request.setAttribute("returnUrl","dms/ListDmsPublicDocument.do?parentID="+request.getParameter("parentID")+"&rootID="+request.getParameter("rootID"));
              return mapping.findForward(WorkflowOperationConstant.WORKFLOW_ASSIGN_USER);
            }  
            //===== For Handle The Second Step IS Dynamic Assign Owner End   ======= 
            String recordStatus = actionForm.getRecordStatus();
            actionForm.reset(mapping, request);
            //init the permission setup data
            this.init(mapping, actionForm, request, response); 
            actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            actionForm.setRootID(rootID);
            actionForm.setParentID(parentID);            
            actionForm.setRecordStatus(recordStatus);
            
            //actionForm.setID(null);
            //actionForm.setReferenceNo("");
            if (DmsOperationConstant.DMS_RECORD_EMPTY.equals(actionForm.getRecordStatus())) {
              //Add By Jim Zhou     2006/11/30      EIP-995     for problem 3
              this.getParentFolderDefaultProfile(mapping, actionForm, request, response) ;
              //Add End
              actionForm.setDocumentType(docType);  
              actionForm.setOpMode("DMS.CREATE_EMTPY_FILE");
              return mapping.findForward(DmsOperationConstant.CREATE_EMPTY_FILE);
            } else {
              //set parent folder profile  
              this.getParentFolderDefaultProfile(mapping, actionForm, request, response) ; 
              actionForm.setDocumentType(docType);                
              actionForm.setOpMode("");     
              actionForm.setRecordStatus("");              
              //if document type is folde ,then returnt to EditDmsDocumentFolder.jsp
              if (DmsDocument.FOLDER_TYPE.equals(((MaintDmsDocumentForm)form).getDocumentType())){
                return mapping.findForward("DMS.MAINT.FORDER");
              }else{
                return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
              }
            }
          }
        }
      } else if (DmsOperationConstant.MOVE_OPERATION.equals(opMode)) {
      // Move operation.
      log.debug("enter move");

      //Add By Jim Zhou       2007/0110       EIP-1292
      MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
      Integer documentID = TextUtility.parseIntegerObj(documentForm.getID());
      DmsDocument document = docRetrievalManager.getDocument(documentID);
      DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
      StringBuffer message = new StringBuffer();

      DmsValidation validation = docValidateManager.validateOperateAction(document, false, "M");
      List lstIdMisRight = validation.getLstIdReject();
      List lstIdBeLocked = validation.getLstIdlocked();
      List lstIdBeDeleted = validation.getLstIdDeleted();
      List lstIdBeArchived = validation.getLstIdArchived();
      List lstIdRelationship = validation.getLstIdHaveRelationship();
      if(!validation.isSuccess()){
          if (!lstIdMisRight.isEmpty() ||
                  !lstIdBeLocked.isEmpty() ||
                  !lstIdBeDeleted.isEmpty() ||
                  !lstIdBeArchived.isEmpty()){
                for (int i=0; i<lstIdMisRight.size(); i++) {
                  this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
                }
                for (int i=0; i<lstIdBeLocked.size(); i++) {
                  this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
                }
                for (int i=0; i<lstIdBeDeleted.size(); i++) {
                  this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
                }
                for (int i=0; i<lstIdBeArchived.size(); i++) {
                  this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
                }
          }
          if (Utility.isEmpty(documentForm.getReturnTo())){
            return mapping.findForward("Home");
          } else {
            ActionForward actionForward = new ActionForward();
            actionForward.setPath("/dms/" + documentForm.getReturnTo());
            return actionForward;
          }
      }
      
      try {
        if ( "".equals(navMode) && !GlobalConstant.NAV_MODE_CHANGE.equals(navMode) ) { 
          // EIP-438 06/12/29 LEE / resolve the problem duplicate name
          this.regeditDuplicateNameCache(request);
          
          //Perform move operation
          boolean moveSuccessed = this.moveRecord2(mapping, actionForm, request, response);

          //addMessage(request, MESSAGE_RECORD_MOVE);
          try {
            //the destination is the personal folder, no need to run workflow 
            Integer targetRootID = documentForm.getTargetRootID() != null ? new Integer(documentForm.getTargetRootID()) : null;
            if(!Utility.isEmpty(targetRootID)){
              DmsRoot moveToRoot=rootRetrievalManager.getRootObject(targetRootID);
              if(!DmsRoot.PERSONAL_ROOT.equals(moveToRoot.getRootType()) && moveSuccessed){
                this.handleWorkflowRoutine(mapping, actionForm, request, response, opMode, navMode);    
              }
            }
            
          } catch (ApplicationException e) {
            this.rollback(request);
            log.error(e, e);
            throw e;
          }
          this.commit(request);

        } //list move page for user selection
        else {
          this.selectRecord(mapping, actionForm, request, response);
          return mapping.findForward(DmsOperationConstant.MOVE_OPERATION);
        }
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      } finally {
        // EIP-438 06/12/29 LEE / resolve the problem duplicate name
        this.unlockDuplicateNameCache(request);
      }
      if (isError(request)) {
        this.selectRecord(mapping, actionForm, request, response);
        actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        return mapping.findForward(DmsOperationConstant.MOVE_OPERATION);
      } else {
        //===== For Handle The Second Step IS Dynamic Assign Owner Begin =======           
        HashMap tmp = (HashMap) request.getAttribute("assignStepMap");
        if (tmp!=null && !tmp.isEmpty()) {
          actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);              
          request.setAttribute("returnUrl","dms/ListDmsPublicDocument.do?parentID="+request.getParameter("parentID")+"&rootID="+request.getParameter("rootID"));
          return mapping.findForward(WorkflowOperationConstant.WORKFLOW_ASSIGN_USER);
        }  
        //===== For Handle The Second Step IS Dynamic Assign Owner End   ======= 
        this.selectRecord(mapping, actionForm, request, response);
        actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        return mapping.findForward(DmsOperationConstant.COPY_MOVE_VIEW);
      }
    }  // COPY operation.
    else if ((DmsOperationConstant.COPY_OPERATION.equals(opMode))|| 
      (DmsOperationConstant.COPY_MORE_OPERATION.equals(opMode))){
      log.debug("enter copy");

      //Add By Jim Zhou       2007/0110       EIP-1292
      MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
      Integer documentID = TextUtility.parseIntegerObj(documentForm.getID());
      DmsDocument document = docRetrievalManager.getDocument(documentID);
      DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
      StringBuffer message = new StringBuffer();

      DmsValidation validation = docValidateManager.validateOperateAction(document, false, "C");
      List lstIdMisRight = validation.getLstIdReject();
      List lstIdBeLocked = validation.getLstIdlocked();
      List lstIdBeDeleted = validation.getLstIdDeleted();
      List lstIdBeArchived = validation.getLstIdArchived();
      List lstIdRelationship = validation.getLstIdHaveRelationship();
      if (!lstIdMisRight.isEmpty() ||
          !lstIdBeLocked.isEmpty() ||
          !lstIdBeDeleted.isEmpty() ||
          !lstIdBeArchived.isEmpty()){
        for (int i=0; i<lstIdMisRight.size(); i++) {
          this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
        }
        for (int i=0; i<lstIdBeLocked.size(); i++) {
          this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
        }
        for (int i=0; i<lstIdBeDeleted.size(); i++) {
          this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
        }
        for (int i=0; i<lstIdBeArchived.size(); i++) {
          this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
        }
        if (Utility.isEmpty(documentForm.getReturnTo())){
          return mapping.findForward("Home");
        } else {
          ActionForward actionForward = new ActionForward();
          actionForward.setPath("/dms/" + documentForm.getReturnTo());
          return actionForward;
        }
      }
      //Add
      
      try {
        if("true".equals(request.getParameter("refreshCopyOpt"))){
    	   this.selectRecord(mapping, actionForm, request, response);
           if(DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType())){
             actionForm.setReferenceNo("");
           }
          return mapping.findForward(DmsOperationConstant.COPY_OPERATION);
        }
        if ( "".equals(navMode) && !GlobalConstant.NAV_MODE_CHANGE.equals(navMode) ) {
          // EIP-438 06/12/29 LEE / resolve the problem duplicate name
          this.regeditDuplicateNameCache(request);
          
          boolean copySuccessed= copyRecord2(mapping, actionForm, request, response);
          
          this.selectRecord(mapping,actionForm,request,response);//Add By Jim.Zhou		2006/08/31		Bug:EIP-116

          //addMessage(request, MESSAGE_RECORD_COPY);
          try {
            //the destination is the personal folder, no need to run workflow 
            Integer targetRootID = documentForm.getTargetRootID() != null ? new Integer(documentForm.getTargetRootID()) : null;
            if(!Utility.isEmpty(targetRootID)){
              DmsRoot moveToRoot=rootRetrievalManager.getRootObject(targetRootID);
              if(!DmsRoot.PERSONAL_ROOT.equals(moveToRoot.getRootType())){
                String tmpDocumentID = actionForm.getID().toString();
                if(!Utility.isEmpty(actionForm.getCopiedDocID())){
                  actionForm.setID(actionForm.getCopiedDocID().toString());  
                }
                if(copySuccessed){
                  this.handleWorkflowRoutine(mapping, actionForm, request, response, opMode, navMode);  
                }
                actionForm.setID(tmpDocumentID);
              }
            }
          } catch (ApplicationException e) {
            this.rollback(request);
            log.error(e, e);
            throw e;
          }
          this.commit(request);
        } else {       
          this.selectRecord(mapping, actionForm, request, response);
          if(DmsDocument.PAPER_DOC_TYPE.equals(document.getDocumentType())){
            actionForm.setReferenceNo("");
          }
          return mapping.findForward(DmsOperationConstant.COPY_OPERATION);
        }
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      } finally {
        this.unlockDuplicateNameCache(request);
      }
      if (isError(request)) {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        String referenceNo=actionForm.getReferenceNo();
        String description=actionForm.getDescription();
        
        //Add by Beyond  2007/04/10  EIP-2084
        if(DmsOperationConstant.COPY_MORE_OPERATION.equals(opMode)){
          actionForm.setOpMode(DmsOperationConstant.COPY_OPERATION);
          actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        }        
        //END
        
        //Add By Jim Zhou     2006/11/01      EIP-117
        try {
          List docDetailsList = docRetrievalManager.retrievalDocumentDetailsList(request);
          if (docDetailsList!=null && docDetailsList.size() > 0){
            actionForm.setDocumentDetails(docDetailsList);
          }
        } catch (Exception ee) {
          log.error(ee, ee);
        }
        
        List tmpudfDetailList = docRetrievalManager.retrievalDocumentDetailsList(request);
        Integer udfID = null;
        if (tmpudfDetailList != null && tmpudfDetailList.size() > 0) {
          udfID = ( (DmsDocumentDetail) tmpudfDetailList.get(0)).getUserDefinedFieldID();
          log.debug("udfID====: " + udfID);
          if (udfID != null) {
            actionForm.setUserDefinedFieldID(udfID.toString());
          }
        } 
        //Add End
        
        this.refreshFormData(mapping, actionForm, request, response); 
        actionForm.setReferenceNo(referenceNo);
        actionForm.setDescription(description);
        return mapping.findForward(DmsOperationConstant.MOVE_OPERATION);
      } else {
        //===== For Handle The Second Step IS Dynamic Assign Owner Begin =======           
        HashMap tmp = (HashMap) request.getAttribute("assignStepMap");
        if (tmp!=null && !tmp.isEmpty()) {
          actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);              
          request.setAttribute("returnUrl","dms/ListDmsPublicDocument.do?parentID="+request.getParameter("parentID")+"&rootID="+request.getParameter("rootID"));
          return mapping.findForward(WorkflowOperationConstant.WORKFLOW_ASSIGN_USER);
        }  
        //===== For Handle The Second Step IS Dynamic Assign Owner End   ======= 
        if(DmsOperationConstant.COPY_MORE_OPERATION.equals(opMode)){

          actionForm.setOpMode(DmsOperationConstant.COPY_OPERATION);
          actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(DmsOperationConstant.COPY_OPERATION);
        }else{

          actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
          return mapping.findForward(DmsOperationConstant.COPY_MOVE_VIEW);      
        }
      }
    }//Refresh mode
    else if (GlobalConstant.NAV_MODE_REFRESH.equals(opMode)) {
      log.debug("refreshing ...");
      try {
        refreshFormData(mapping, actionForm, request, response);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
      } else {
        if (DmsDocument.FOLDER_TYPE.equals(((MaintDmsDocumentForm)form).getDocumentType())){
            return mapping.findForward("DMS.MAINT.FORDER");
        }else{        
            return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
        }
      }
    }//Rename mode
    else if (DmsOperationConstant.RENAME_OPERATION.equals(opMode)) {
      // Insert operation.

      log.debug("enter rename");
      try {
        if (!Utility.isEmpty(actionForm.getNavMode())) {
          // EIP-438 06/12/29 LEE / resolve the problem duplicate name
          this.regeditDuplicateNameCache(request);
          this.renameRecord(mapping, actionForm, request, response);
          this.commit(request);
          addMessage(request, MESSAGE_RECORD_RENAME);
        } else {
          this.selectRecord(mapping, actionForm, request, response);
          actionForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
          return mapping.findForward(DmsOperationConstant.RENAME_OPERATION);
        }

      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      } finally {
        // EIP-438 06/12/29 LEE / resolve the problem duplicate name
        this.unlockDuplicateNameCache(request);
      }
      if (isError(request)) {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);
        return mapping.findForward(DmsOperationConstant.RENAME_OPERATION);
      } else {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        return mapping.findForward(DmsOperationConstant.RENAME_VIEW);
      }

    }
    else if(DmsOperationConstant.VIEW_PAPER_DOCUMENT_INFO.equals(opMode)){
      log.debug("work flow View paper document info");
      try{
       // form = docRetrievalManager.getAllDocumentRelatedInfo(new Integer(((MaintDmsDocumentForm)form).getID()));
       
        ((MaintDmsDocumentForm)form).setNavMode(GlobalConstant.NAV_MODE_VIEW);
        ((MaintDmsDocumentForm)form).setOpMode(DmsOperationConstant.VIEW_PAPER_DOCUMENT_INFO);
    
        this.getPaperDocByRefNo(mapping, actionForm, request, response);  
 
        if ( !this.getSessionContainer(request).getPermissionManager().hasAccessRight ( GlobalConstant.OBJECT_TYPE_DOCUMENT, Integer.valueOf(((MaintDmsDocumentForm)form).getID()), "R" ) ) {
            ((MaintDmsDocumentForm)form).setID(null);
            throw new ApplicationException(ErrorConstant.COMMON_UNAUTHORIZED_ACCESS);        
        } 

          this.selectRecord(mapping, actionForm, request, response);
      
      }catch (ApplicationException appEx) {
        handleApplicationException(request, appEx);
      }
      return mapping.findForward(DmsOperationConstant.VIEW_PAPER_DOCUMENT_INFO);
    } // Else Case when normal opMode
    else {
      ActionForward tmpActionForward=null;
      if(!Utility.isEmpty(navMode) && navMode.equals(GlobalConstant.NAV_MODE_PREVIEW)){
        if(!Utility.isEmpty(request.getParameter("sCurFunctionCode"))){
          actionForm.setCurFunctionCode(request.getParameter("sCurFunctionCode"));
        }
        if(this.allowGetList(mapping, actionForm, request, response)){
          this.selectRecord(mapping, actionForm, request, response);  
        }else{
          request.setAttribute("notAllowRead","YES");
          actionForm.reset(mapping,request);
        }     
        DmsDocument dmsDocument=docRetrievalManager.getDocument(TextUtility.parseIntegerObj(actionForm.getID()));
        if(DmsDocument.EMAIL_DOC_TYPE.equals(dmsDocument.getDocumentType())){
          tmpActionForward=mapping.findForward(navMode);
        }else{
          Integer updateAlertTypeID = null;
          try{
            AlertManager am = new AlertManager(sessionContainer,conn);
            UpdateAlert updateAlert = am.getUpdateAlertByObjectTypeObjectID(GlobalConstant.OBJECT_TYPE_DOCUMENT,TextUtility.parseIntegerObj(actionForm.getObjectID()));
            if(!Utility.isEmpty(updateAlert)){
              UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer,conn);
              UpdateAlertType updateAlertType = (UpdateAlertType)updateAlertTypeDAO.getByupdateAlertID(updateAlert.getID());
              updateAlertTypeID = updateAlertType.getID();
            }
         
            String tempRedirectURL ="/EditMessageDetail.do?messageType=documentNotification&objectid="+actionForm.getObjectID()+"&updateAlertTypeID="+updateAlertTypeID+"&isList=no&isFromEmail=yes'";
            RequestDispatcher rd = request.getRequestDispatcher(tempRedirectURL);
            rd.forward(request,response);
            return null;
          }catch(Exception e){
            log.error("Forward Error Occor",e);
          }  
        }             
      } else {
        //Add By Jim Zhou       2007/0110       EIP-1292
        if (GlobalConstant.NAV_MODE_EDIT.equals(navMode) 
            || GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
          Integer documentID = TextUtility.parseIntegerObj(documentForm.getID());
          DmsDocument document = docRetrievalManager.getDocument(documentID);
          DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
          if (!(DmsDocument.COMPOUND_DOC_TYPE.equals(document.getDocumentType()) && GlobalConstant.NAV_MODE_VIEW.equals(navMode))){
            StringBuffer message = new StringBuffer();
  
            DmsValidation validation = docValidateManager.validateOperateAction(document, false, "E");
            List lstIdMisRight = validation.getLstIdReject();
            List lstIdBeLocked = validation.getLstIdlocked();
            List lstIdBeDeleted = validation.getLstIdDeleted();
            List lstIdBeArchived = validation.getLstIdArchived();
            List lstIdRelationship = validation.getLstIdHaveRelationship();
            if (!validation.isSuccess()){
              for (int i=0; i<lstIdMisRight.size(); i++) {
                this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
              }
              for (int i=0; i<lstIdBeLocked.size(); i++) {
                this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
              }
              for (int i=0; i<lstIdBeDeleted.size(); i++) {
                this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
              }
              for (int i=0; i<lstIdBeArchived.size(); i++) {
                this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
              }
              
              if (Utility.isEmpty(documentForm.getReturnTo())){
                return mapping.findForward("Home");
              } else {
                ActionForward actionForward = new ActionForward();
                actionForward.setPath("/dms/" + documentForm.getReturnTo());
                return actionForward;
              }
            }
          }
        }
        //Add End
        tmpActionForward = super.execute(mapping, form, request, response);
        if (GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode) || GlobalConstant.OP_MODE_UPDATE_NEW.equals(opMode)) {
          ((MaintDmsDocumentForm)form).setParentID(parentID);
          ((MaintDmsDocumentForm)form).setRootID(rootID);
          ((MaintDmsDocumentForm)form).setDocumentType(docType);
        }                
      }
      if(!GlobalConstant.NAV_MODE_EDIT.equals(navMode) && !GlobalConstant.NAV_MODE_PREVIEW.equals(navMode)){
         this.getParentFolderDefaultProfile(mapping, actionForm, request, response);    
      }
      //if document type is folde ,then returnt to EditDmsDocumentFolder.jsp
      if (DmsDocument.FOLDER_TYPE.equals(((MaintDmsDocumentForm)form).getDocumentType())){
        return mapping.findForward("DMS.MAINT.FORDER");
      }else{
        return tmpActionForward;  
      }
      
    }
  }
  
  
  public void init(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    super.init(mapping, form, request, response);
    MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;    
    if(!Utility.isEmpty(actionForm.getObjectType())){
      com.dcivision.user.dao.UserPermissionInheritDAObject userPermInheritDAO = new com.dcivision.user.dao.UserPermissionInheritDAObject(this.getSessionContainer(request), this.getConnection(request));
      com.dcivision.user.bean.UserPermissionInherit tmpUserPermissionInherit = (com.dcivision.user.bean.UserPermissionInherit)userPermInheritDAO.getObjectByObjectTypeObjectID(actionForm.getObjectType(), new Integer(actionForm.getObjectID()));
      if (tmpUserPermissionInherit == null) {
        if(!SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_NOT_INHERIT_FROM_PARENT)){
          actionForm.setInheritanceFlag(GlobalConstant.TRUE);
        } else{
          actionForm.setInheritanceFlag(null);  
        }        
      } else {
        actionForm.setInheritanceFlag(null);
      }
    }else{
      if(!SystemParameterFactory.getSystemParameterBoolean(SystemParameterConstant.DMS_NOT_INHERIT_FROM_PARENT)){
        actionForm.setInheritanceFlag(GlobalConstant.TRUE);
      } else{
        actionForm.setInheritanceFlag(null);  
      }   
    }
  }
  /**
   * Check DmsAttachment size with this workflow unload path of public folder size,and
   * check total of document size and attachment size when document path with the 
   * same unload file path,only check attachment size when document path and unload 
   * file path is not the same.
   * Call form create document.
   * @param form
   * @param dmsDocument  
   * @param createFile   
   * @param request
   * @throws ApplicationException
   * @author Bill
   */
  private void checkDmsAttachmentWithPublicFolderSizeInCreateDocument(AbstractActionForm form,DmsDocument dmsDocument,boolean createFile,HttpServletRequest request) throws ApplicationException{
    if (form instanceof WorkflowActionFormInterface && this instanceof WorkflowActionInterface && GlobalConstant.TRUE.equals(((WorkflowActionFormInterface)form).getSubmitSystemWorkflow())) {
      //Get attachment list
      WorkflowActionFormInterface wfaForm = (WorkflowActionFormInterface)form;
      MultipleFileUploadUtil uploadUtil = new MultipleFileUploadUtil(this.getSessionContainer(request));
      List attachmentList = uploadUtil.getWorkflowAttachmentList(wfaForm.getFileNames(), WorkflowProgressAttachment.ATTACHED_SINGLE_FILE);
      WorkflowProgressAttachment attachment = null;
      if(Utility.isEmpty(attachmentList)){
        return;
      }
      
      //Get current workflow record
      WorkflowRecordDAObject workflowRecordDAO= new WorkflowRecordDAObject(this.getSessionContainer(request), this.getConnection(request));
      String workflowRecordID=wfaForm.getWorkflowRecordID();
      //if current public folder binded many workflow,the workflow recordID looks like this"ID|N|0"
      if(workflowRecordID.indexOf("|")>0){
        workflowRecordID=workflowRecordID.substring(0,workflowRecordID.indexOf("|"));
      }
      Integer workfloRecordID=new Integer(workflowRecordID);
      WorkflowRecord currentRecord = (WorkflowRecord) workflowRecordDAO.getObjectByID(workfloRecordID);
      
      //Get current document root ID
      DmsDocumentDAObject dmsDocumentDAO=new DmsDocumentDAObject(this.getSessionContainer(request),this.getConnection(request));
      DmsDocument document=(DmsDocument)dmsDocumentDAO.getDocumentByID(currentRecord.getParentID(),GlobalConstant.RECORD_STATUS_ACTIVE);
      Integer rootID=Utility.isEmpty(document)?new Integer(1):document.getRootID();
      DocumentValidateManager docValidateManager = new DocumentValidateManager(this.getSessionContainer(request), this.getConnection(request));
      int documentSize=dmsDocument.getItemSize().intValue();         //Bind document size
      
      if(rootID.equals(dmsDocument.getRootID())){
	    for(int index=0;index<attachmentList.size();index++){
	      attachment=(WorkflowProgressAttachment)attachmentList.get(index);
	      int attachmentSize = attachment.getContentSize().intValue();   //Acctachment size	      
	      //TotalSize is total of bind document and attachment
	      Integer totalSize=new Integer(documentSize+attachmentSize);
	      if (createFile) {
	        //Dummy document item size data
	        dmsDocument.setItemSize(totalSize);
	        //Check public folder size with dummy data	          
	        docValidateManager.checkStorageLimitAvailable(dmsDocument);
	        docValidateManager.release();
	        //Comeback document item size
	        dmsDocument.setItemSize(new Integer(documentSize));
	      }
	    }
      }else{
        docValidateManager.checkDmsAttachmentWithPublicFolderSize(wfaForm.getFileNames(), rootID);
      }
    }
  }
  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    String navMode = (form!=null) ? form.getNavMode() : request.getParameter("navMode");
    
    Integer documentID = TextUtility.parseIntegerObj(form.getID());
    DmsDocument document = docRetrievalManager.getDocument(documentID);
    
    if (DmsDocument.DOCUMENT_LINK.equals(document.getDocumentType())){
       MtmDocumentRelationshipDAObject docRelationshipDAO = new MtmDocumentRelationshipDAObject(sessionContainer, conn);
       Integer targetDocID = docRelationshipDAO.getTargetDocIDByRelatedDocID(documentID, document.getDocumentType());
       DmsDocument targetDoc = docRetrievalManager.getDocument(targetDocID);
       if (targetDoc==null || GlobalConstant.RECORD_STATUS_INACTIVE.equals(targetDoc.getRecordStatus())){
         this.addError(request, DmsErrorConstant.TARGET_DOCUMENT_NOT_FOUND);
       }
       //Edit By Jim Zhou      2007/03/16        EIP-1663
       if (GlobalConstant.NAV_MODE_EDIT.equals(navMode)) {
         document = targetDoc;
       } else {
         request.setAttribute("targetDoc", targetDoc);
       }
       //Edit End
       docRelationshipDAO=null;
     }

    MaintDmsDocumentForm newForm = (MaintDmsDocumentForm) form;
    
    //get parentFoler profile
    if(!Utility.isEmpty(newForm.getClearIndexFlag()) && !newForm.getClearIndex()){
    	/*
    	 * joan.xiong update code for bug EIP-1112 by 2007/01/10
    	 */
    	if(!Utility.isEmpty(newForm.getUserDefinedFieldID()) && Utility.isEmpty(request.getParameter("isChangeUDFID"))){
    		List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(newForm.getUserDefinedFieldID()));
    		newForm.setUdfDetailList(udfDetailList);
        	List docDetailsList = docRetrievalManager.retrievalDocumentDetailsList(request);
            if (!Utility.isEmpty(docDetailsList)){
            	newForm.setDocumentDetails(docDetailsList);
            }
    	}else{
    		if(!Utility.isEmpty(newForm.getDestinationID())){
    			newForm.setParentID(newForm.getDestinationID());
    		}
    		List docDetailList = docRetrievalManager.getDocumentDetailList(TextUtility.parseIntegerObj(newForm.getID()));
    		if(!Utility.isEmpty(docDetailList)){
    			newForm.setFormData(document);
    			DmsDocumentDetail docDetail = (DmsDocumentDetail)docDetailList.get(0);
    			newForm.setUserDefinedFieldID(docDetail.getUserDefinedFieldID().toString());
    			newForm.setUdfDetailList(docRetrievalManager.getUDFDetailList(docDetail.getUserDefinedFieldID()));
    			newForm.setDocumentDetails(docDetailList);
    		}else{
    			newForm.setFormData(document);
    			this.getParentFolderDefaultProfile(mapping,form,request,response);
    		}
    	}
    
    }else if (!Utility.isEmpty(newForm.getClearIndexFlag()) && newForm.getClearIndex() && !("E".equals(request.getParameter("opt")))){
      newForm.setUserDefinedFieldID(null);
      newForm.setUserDef1(null);
      newForm.setUserDef2(null);
      newForm.setUserDef3(null);
      newForm.setUserDef4(null);
      newForm.setUserDef5(null);
      newForm.setUserDef6(null);
      newForm.setUserDef7(null);
      newForm.setUserDef8(null);
      newForm.setUserDef9(null);
      newForm.setUserDef10(null);
    }else{        
        if ((DmsOperationConstant.COPY_OPERATION.equals(form.getOpMode()) || DmsOperationConstant.COPY_MORE_OPERATION.equals(form.getOpMode()) || DmsOperationConstant.MOVE_OPERATION.equals(form.getOpMode())) //Update By Jim Zhou          2007/03/03      EIP-1703
                && GlobalConstant.NAV_MODE_CHANGE.equals(newForm.getNavMode())){
            List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(newForm.getUserDefinedFieldID()));
            newForm.setUdfDetailList(udfDetailList);   
            List docDetailsList = docRetrievalManager.retrievalDocumentDetailsList(request);
            if (docDetailsList!=null && docDetailsList.size() > 0){
            	newForm.setDocumentDetails(docDetailsList);
            }
        }else{    
            List docDetailList = docRetrievalManager.getDocumentDetailList(documentID);
            if (docDetailList!=null){
                newForm.setFormData(document, docDetailList);
            } else {
                newForm.setFormData(document);
            }
            //  Use for List the target User Defined Fields Detail
            if (newForm.getUserDefinedFieldID() !=null){
                List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(newForm.getUserDefinedFieldID()));
                newForm.setUdfDetailList(udfDetailList);
            	if (GlobalConstant.NAV_MODE_EDIT.equals(newForm.getNavMode())&& "E".equals(request.getParameter("opt")) && udfDetailList.size()<1){
            		newForm.setUseDefaultProfile("");
            	}
            }
        }
    }

    //reset the original root id and parent id for copy and move; used in the tree selection
    if (DmsOperationConstant.COPY_OPERATION.equals(form.getOpMode()) || DmsOperationConstant.COPY_MORE_OPERATION.equals(form.getOpMode()) || DmsOperationConstant.MOVE_OPERATION.equals(form.getOpMode())) { //Update By Jim Zhou          2007/03/03      EIP-1703
      newForm.setParentID(parentID);
      newForm.setRootID(rootID);
      newForm.setDocumentType(docType);
      newForm.setDocumentType(document.getDocumentType());
    }
    sessionContainer = null;
    conn = null;
    docRetrievalManager.release();
  }

  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    boolean createFile = false;
    InputStream inputStream = null;
    FormFile formFile = null;

    //Modification for Scanned Document import
    FormFile scanIndex = null;
    InputStream scanFileInputStream = null;
    InputStream scanDocInputStream = null;
    Integer scanFileSize = null;

    //Modification for Scanned FullTextDocument import
    FormFile fullTextIndex = null;
    InputStream fullTextFileInputStream = null;

    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;

    log.debug("inserting record , doc type = "+documentForm.getDocumentType() + " rootID  = "+documentForm.getRootID() + " parentID = "+documentForm.getParentID());
    DmsDocument newDocument = null;
    String submitSystemWorkflow = null;
    String workflowRecordID = null;
    try {

      if (DmsDocument.DOCUMENT_TYPE.equals(documentForm.getDocumentType()) || DmsDocument.COMPOUND_DOC_TYPE.equals(documentForm.getDocumentType()) || DmsDocument.PAPER_DOC_TYPE.equals(documentForm.getDocumentType())) {
        if (Utility.isEmpty(documentForm.getEmailAttachment())){
          //Create Document
          formFile = documentForm.getUploadFile();
          if (formFile !=null) {
            inputStream = formFile.getInputStream();
            log.debug("target document size: " + formFile.getFileSize());
          }

          DmsDocument dmsDocument = (DmsDocument) documentForm.getFormData();
          String fileName="";            
          //Update By Jim Zhou    2006/11/29      EIP-997       add "!(DmsOperationConstant.DMS_RECORD_EMPTY.equals(dmsDocument.getRecordStatus())) &&"
          if(!DmsDocument.PAPER_DOC_TYPE.equals(documentForm.getDocumentType()) && !(DmsOperationConstant.DMS_RECORD_EMPTY.equals(dmsDocument.getRecordStatus())) && !"odma".equals(odmaProcess)){
            fileName= TextUtility.formatFileName(request.getParameter("trueFileName"));
          }
          if (Utility.isEmpty(fileName)) {
            fileName = documentForm.getTrueFileName();
          }
          if(DmsDocument.PAPER_DOC_TYPE.equals(documentForm.getDocumentType())){
            fileName=documentForm.getDocumentName(); 
          }
          
          int fileNameLength = TextUtility.parseInteger(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_MAX_UPLOAD_FILENAME_LENGTH));
          if(fileName.length()>fileNameLength){
            throw new ApplicationException(ErrorConstant.DMS_MESSAGE_UPLOAD_FILE_NAME_LENGTH_EXCEEDED,null,SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_MAX_UPLOAD_FILENAME_LENGTH));
          }
          documentForm.setDocumentName(fileName);
          documentForm.setItemStatus(DmsVersion.AVAILABLE_STATUS);
          dmsDocument.setDocumentName(fileName);
          dmsDocument.setItemStatus(DmsVersion.AVAILABLE_STATUS);
          if (formFile!=null) {
            dmsDocument.setItemSize(new Integer(formFile.getFileSize()));
            documentForm.setItemSize(TextUtility.formatIntegerObj(dmsDocument.getItemSize()));
          }else{
            dmsDocument.setItemSize(new Integer(0));
            documentForm.setItemSize("0");
          }

          try {
            List docDetailsList = docRetrievalManager.retrievalDocumentDetailsList(request);
            if (docDetailsList!=null && docDetailsList.size() > 0){
              dmsDocument.setDocumentDetails(docRetrievalManager.retrievalDocumentDetailsList(request));              
              //add to form first, handle exception case
              documentForm.setDocumentDetails(docDetailsList);
            }
          } catch (Exception ee) {
            log.error(ee, ee);
          }
          /* Special handling for validation on Scanned dmsDocument  */
          scanIndex = documentForm.getScanFile();
          fullTextIndex = documentForm.getFullTextFile();
          boolean  withScanWorkflow = false;
          Boolean additionalAction = new Boolean(false);
          
          // if have workflow ,check the due date if is not empty
          if(!Utility.isEmpty(request.getParameter("workflowRecordID"))&&
                  !"null".equals(request.getParameter("nextStepDueDates"))){
              WorkflowStepManager workflowStepManager =  new WorkflowStepManager(this.getSessionContainer(request),
                      this.getConnection(request)); 
              String workflowRecordIDStr = request.getParameter("workflowRecordID");
              if(workflowRecordIDStr.indexOf("|") >0 ){
                  workflowRecordIDStr = workflowRecordIDStr.substring(0,workflowRecordIDStr.indexOf("|"));
              }                
                
              Integer workflowRecordIDInt = TextUtility.parseIntegerObj(workflowRecordIDStr);
              String nextStepDueDates = request.getParameter("nextStepDueDates");
              workflowStepManager.checkSecondStepDueDates(workflowRecordIDInt,nextStepDueDates);
          }          
          if("odma".equals(odmaProcess) && scanIndex!=null){
            
            
            scanFileInputStream = scanIndex.getInputStream();
            scanDocInputStream = scanIndex.getInputStream();            
            //get document info from scanned file index, and create the folder is required
            try {
              this.documentAnalyzer = (DmsDocumentAnalyzer) Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.
                  DMS_DOCUMENT_ANALYZER_CLASS)).newInstance();
            } catch (Exception cnfe) {
              log.error(cnfe, cnfe);
            }
            additionalAction = this.documentAnalyzer.analyzeForCustomizationAction(sessionContainer, conn, documentForm, scanDocInputStream);
           
            this.commit(request);
            
            dmsDocument.setDescription(this.documentAnalyzer.getDescription());
            dmsDocument.setReferenceNo(this.documentAnalyzer.getReferenceNo());
            
            
            List defaultProfileSettingList = (List) request.getSession().getServletContext().getAttribute("DMS_DEF_PROFILE");
            dmsDocument.setUserDef1(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef1(), 1));
            dmsDocument.setUserDef2(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef2(), 2));
            dmsDocument.setUserDef3(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef3(), 3));
            dmsDocument.setUserDef4(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef4(), 4));
            dmsDocument.setUserDef5(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef5(), 5));
            dmsDocument.setUserDef6(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef6(), 6));
            dmsDocument.setUserDef7(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef7(), 7));
            dmsDocument.setUserDef8(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef8(), 8));
            dmsDocument.setUserDef9(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef9(), 9));
            dmsDocument.setUserDef10(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef10(), 10));
            //process scan index for UDF, and get document details
            if (!additionalAction.booleanValue()) {
              try {
                List scanFileDetailList = this.parseUploadedUDFIndex(scanFileInputStream, request);
                if (scanFileDetailList != null) {
                  log.debug("Processed Scan File Size: " + scanFileDetailList.size());
                  dmsDocument.setDocumentDetails(scanFileDetailList);
                }
              } catch (Exception e) {
                log.error(e, e);
              }
            }
            
            List tmpudfDetailList = dmsDocument.getDocumentDetails();
            Integer udfID = null;
            if (tmpudfDetailList != null && tmpudfDetailList.size() > 0) {
              udfID = ( (DmsDocumentDetail) tmpudfDetailList.get(0)).getUserDefinedFieldID();
              log.debug("udfID====: " + udfID);
              if (udfID != null) {
                dmsDocument.setUserDefinedFieldID(udfID);
              }
            }                        
          }
          if (!("odma".equals(odmaProcess))&&scanIndex!=null ) {
            scanFileInputStream = scanIndex.getInputStream();
            scanDocInputStream = scanIndex.getInputStream();
            log.debug("scanned index filename: " + scanIndex.getFileName() + " size = " + scanIndex.getFileSize());

            //Define new User Defined Type

            //get document info from scanned file index, and create the folder is required
            try {
              this.documentAnalyzer = (DmsDocumentAnalyzer) Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.
                DMS_DOCUMENT_ANALYZER_CLASS)).newInstance();
            } catch (Exception cnfe) {
              log.error(cnfe, cnfe);
            }
            additionalAction = this.documentAnalyzer.analyze(sessionContainer, conn, documentForm, scanDocInputStream);
            this.commit(request);
            
            dmsDocument.setDocumentName(this.documentAnalyzer.getDocumentName());
            dmsDocument.setDescription(this.documentAnalyzer.getDescription());
            dmsDocument.setReferenceNo(this.documentAnalyzer.getReferenceNo());

            List defaultProfileSettingList = (List) request.getSession().getServletContext().getAttribute("DMS_DEF_PROFILE");
            dmsDocument.setUserDef1(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef1(), 1));
            dmsDocument.setUserDef2(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef2(), 2));
            dmsDocument.setUserDef3(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef3(), 3));
            dmsDocument.setUserDef4(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef4(), 4));
            dmsDocument.setUserDef5(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef5(), 5));
            dmsDocument.setUserDef6(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef6(), 6));
            dmsDocument.setUserDef7(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef7(), 7));
            dmsDocument.setUserDef8(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef8(), 8));
            dmsDocument.setUserDef9(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef9(), 9));
            dmsDocument.setUserDef10(this.setDefaultProfileValue(defaultProfileSettingList, documentAnalyzer.getUserDef10(), 10));

            /* Workflow handling for scanned in document */
            documentForm.setSubmitSystemWorkflow(this.documentAnalyzer.getSubmitSystemWorkflow());
            submitSystemWorkflow=this.documentAnalyzer.getSubmitSystemWorkflow();
            documentForm.setWorkflowRecordID(this.documentAnalyzer.getWorkflowRecordID());
            workflowRecordID=this.documentAnalyzer.getWorkflowRecordID();
            documentForm.setWorkflowComment("Scanned Document");
            if ("0".equals(documentForm.getWorkflowRecordID())) {
              DmsDocument personalFolder = docRetrievalManager.getDocumentByNameParentIDCreatorID(DmsOperationConstant.DMS_PERSONAL_ROOT, new Integer(0), sessionContainer.getUserRecordID());
              if (personalFolder != null) {
                dmsDocument.setParentID(personalFolder.getID());
                dmsDocument.setRootID(personalFolder.getRootID());
                documentForm.setSubmitSystemWorkflow(null);
                submitSystemWorkflow = null;
                documentForm.setWorkflowRecordID(null);
                workflowRecordID = null;
                documentForm.setWorkflowComment(null);
              }
            }else{
              dmsDocument.setParentID(this.documentAnalyzer.getParentID());
              dmsDocument.setRootID(this.documentAnalyzer.getRootID());
            }
            /* End Workflow handling for scanned in document */

            dmsDocument.setCreateType(DmsOperationConstant.DMS_CREATE_BY_UPLOAD);
            //check for special case for additional action
            Integer ID = null;
            ID = this.documentAnalyzer.getID();
            if (ID != null) {
              dmsDocument.setID(ID);
              documentForm.setOpMode(this.documentAnalyzer.getOpMode());
            }
            //process scan index for UDF, and get document details
            if (!additionalAction.booleanValue()) {
              try {
                List scanFileDetailList = this.parseUploadedUDFIndex(scanFileInputStream, request);
                if (scanFileDetailList != null) {
                  log.debug("Processed Scan File Size: " + scanFileDetailList.size());
                  dmsDocument.setDocumentDetails(scanFileDetailList);
                }
              } catch (Exception e) {
                log.error(e, e);
              }
            }

            List tmpudfDetailList = dmsDocument.getDocumentDetails();
            Integer udfID = null;
            if (tmpudfDetailList != null && tmpudfDetailList.size() > 0) {
              udfID = ( (DmsDocumentDetail) tmpudfDetailList.get(0)).getUserDefinedFieldID();
              log.debug("udfID====: " + udfID);
              if (udfID != null) {
                dmsDocument.setUserDefinedFieldID(udfID);
              }
            }

          }

          //Check to see if the insert document is a empty file
          if (DmsOperationConstant.DMS_RECORD_EMPTY.equals(dmsDocument.getRecordStatus()) ) {
            createFile = false;
          } else {
            createFile = true;
          }
          log.debug("create file: " + createFile + " parentID " + dmsDocument.getParentID());
          log.debug("additionalAction file: " + additionalAction);

          /*******************************************************
           * TODO: DmsDocument Record status various handling: Workflow, EmptyFile
           *******************************************************/
          /*Check record status, to see wich operation the document is creating */
          if (!DmsOperationConstant.DMS_RECORD_EMPTY.equals(dmsDocument.getRecordStatus())) {
            dmsDocument.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
          }

          /* Special handling for validation on FullText from dmsDocument  */
          fullTextIndex = documentForm.getFullTextFile();
          if (fullTextIndex != null) {
            String fullTextName = String.valueOf(dmsDocument.getDocumentName().substring(0, dmsDocument.getDocumentName().length() - 4)) + ".txt";
            dmsDocument.setScanDocumentForFullText(true);
            fullTextFileInputStream = fullTextIndex.getInputStream();
            log.debug("scanned index filename: " + fullTextIndex.getFileName() + " size = " + fullTextIndex.getFileSize());
          }

          /* Call regular document creation if no additonal action analyzed from the DmsDocumentAnalyzer */
          if (!additionalAction.booleanValue()) {
            log.info("going to create file status = " + dmsDocument.getRecordStatus());
            if(DmsDocument.PAPER_DOC_TYPE.equals(documentForm.getDocumentType())){
              dmsDocument.setCreatePhysicalFile(false);
              createFile=false;
            }
            if("paraScan".equals(odmaProcess)){
               try{
            	   DocumentValidateManager manager = new DocumentValidateManager(sessionContainer,conn);
                   String oldFileName = dmsDocument.getDocumentName();
                   String newFileName = dmsDocument.getDocumentName();
                   String fileNameOri = oldFileName.substring(0,oldFileName.lastIndexOf("."));
                   String fileNameExt = oldFileName.substring(oldFileName.lastIndexOf("."));
                   int fileNameRenameIndex = 1;
                   boolean checDuplicate = true;
            	   do{
            		 dmsDocument.setDocumentName(newFileName);
            		 checDuplicate = manager.checkNameExistence(dmsDocument);
            		 newFileName = fileNameOri + "("+ fileNameRenameIndex+ ")" + fileNameExt;      
            	     fileNameRenameIndex++; 
            	   }while(checDuplicate==true); 
               }catch(Exception e){
                 log.error(e, e);
               }
            }
            //Bill add for EIP-1958 start
            //Check for available space with attachment size and bind document size
            this.checkDmsAttachmentWithPublicFolderSizeInCreateDocument(form, dmsDocument, createFile, request);
            newDocument = docOperationManager.createDocument(dmsDocument, inputStream, createFile, fullTextFileInputStream);
      
            //Check for empty file, call check out immediately to lock the empty file
            if (DmsOperationConstant.DMS_RECORD_EMPTY.equals(dmsDocument.getRecordStatus())) {
              VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
              versionControlManager.checkoutDocument(DmsVersion.EXCLUSIVE_LOCK, newDocument);
              versionControlManager.release();
            }
          } else { //got additonal action
            log.info("going to check in file status = " + dmsDocument.getRecordStatus());
            VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
            DmsVersion version = new DmsVersion();
            version.setDocumentID(dmsDocument.getID());
            version.setItemSize(dmsDocument.getItemSize());
            version.setItemStatus(dmsDocument.getItemStatus());
            version.setCreateType(dmsDocument.getCreateType());
            version.setRecordStatus(dmsDocument.getRecordStatus());
            version = versionControlManager.checkinDocument(true, DmsOperationConstant.CREATE_NEW_CHECKIN, dmsDocument.getID(), version, inputStream, fullTextFileInputStream);
            versionControlManager.release();

            //retrieval the new document info
            newDocument = docRetrievalManager.getDocument(dmsDocument.getID());
          }
        }
      } else if (DmsDocument.FOLDER_TYPE.equals(documentForm.getDocumentType())) { //End of Document Handling
        DmsDocument dmsDocument = (DmsDocument) documentForm.getFormData();
        dmsDocument.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
        dmsDocument.setItemStatus(DmsVersion.AVAILABLE_STATUS);
        
       // operate profile 
        if(!Utility.isEmpty(documentForm.getUserDefinedFieldID())){
            dmsDocument.setUserDefinedFieldID(TextUtility.parseIntegerObj(documentForm.getUserDefinedFieldID()));
        }
        dmsDocument.setDocumentDetails(docRetrievalManager.retrievalDocumentDetailsList(request));

        if (Utility.isEmpty(dmsDocument.getDocumentName()) || "".equals(dmsDocument.getDocumentName().trim())){
          throw new EmptyContentException(DmsErrorConstant.EMPTY_FOLDER_NAME);
        }
        // create folder
      
        
        if("SCAN".equals(documentForm.getReturnTo())||"TEST".equals(documentForm.getReturnTo())){
         
          //response.getWriter().write("$$$$it is testing folder");
          newDocument = docOperationManager.createFolderFromScan(dmsDocument);
  
          
          if(newDocument==null){
            request.setAttribute("PARENT_FOLDER_ID","");
          }else{
            request.setAttribute("PARENT_FOLDER_ID",newDocument.getID().toString());
          }
          
        }else{
          //create folder for  case not from scanning
          newDocument = docOperationManager.createFolder(dmsDocument);
        }
        
      }
      documentForm.setFormData(newDocument);

      documentForm.setID(TextUtility.formatIntegerObj(newDocument.getID()));
      documentForm.setUdfDetailList(newDocument.getUdfDetailList());
      documentForm.setDocumentDetails(newDocument.getDocumentDetails());
      if (!Utility.isEmpty(submitSystemWorkflow) && !Utility.isEmpty(workflowRecordID)){
        documentForm.setSubmitSystemWorkflow(submitSystemWorkflow);
        documentForm.setWorkflowRecordID(workflowRecordID);
      }

      String path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(parentID));
      request.setAttribute("location", path);

      sessionContainer = null;
      docRetrievalManager.release();
      docOperationManager.release();

      //insert permission data
      if("TRUE".equals(documentForm.getSetPermission())){
        documentForm.setObjectID(TextUtility.formatIntegerObj(newDocument.getID()));      
        this.updateInheritanceFlag(mapping, form, request, response);
        this.updatePermissionObjects(mapping, form, request, response);
      }
      
      
    } catch (IOException ioe) {
      log.error(ioe, ioe);
    } finally {
      conn=null;
    }
  }

  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    
    //get old Document Object
    DmsDocumentDAObject dmsDocumentDAObject = new DmsDocumentDAObject(sessionContainer,conn);    
    DmsDocument oldDocument = (DmsDocument) dmsDocumentDAObject.getObjectByID(TextUtility.parseIntegerObj(documentForm.getID()));
    
    // LEE 06/12/18 EIP-1166 Edit index do not need to update permission 
    if (!GlobalConstant.NAV_MODE_EDIT.equals(documentForm.getNavMode())) {
      super.updatePermissionObjects(mapping, form, request, response);  
    }
    
    DmsDocument document = (DmsDocument) documentForm.getFormData();
    try {       
      //insert the reminder notification record
      if (Utility.isEmpty(oldDocument.getReminderType())&&!Utility.isEmpty(document.getReminderType())) {
        insertReminderNotification(sessionContainer,conn,document);         
      }
        
      document.setDocumentDetails(docRetrievalManager.retrievalDocumentDetailsList(request));
      //Delete the old one for update
      List oldDetails = docRetrievalManager.getDocumentDetailList(document.getID());
      if (!Utility.isEmpty(oldDetails) && oldDetails.size() > 0 ) {
        DmsDocumentDetail oldDmsDetail = (DmsDocumentDetail) oldDetails.get(0);
        Integer oldUDFID = oldDmsDetail.getUserDefinedFieldID();

        if (!Utility.isEmpty(documentForm.getUserDefinedFieldID()) && TextUtility.parseInteger(documentForm.getUserDefinedFieldID()) != oldUDFID.intValue() ){

          docOperationManager.deleteDocumentDetailByDocumentID(document.getID());
          List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(documentForm.getUserDefinedFieldID()));
          documentForm.setUdfDetailList(udfDetailList);
        }
        if(Utility.isEmpty(documentForm.getUserDefinedFieldID())){
          docOperationManager.deleteDocumentDetailByDocumentID(document.getID());
          document.setDocumentDetails(null);
        }
      }

      DmsDocument newDocument = docOperationManager.updateDocument(document);
      documentForm.setUdfDetailList(newDocument.getUdfDetailList());
      documentForm.setDocumentDetails(newDocument.getDocumentDetails());
      documentForm.setFormData(newDocument, newDocument.getDocumentDetails());
      String path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(parentID));
      request.setAttribute("location", path);

      sessionContainer = null;
      docRetrievalManager.release();
      docOperationManager.release();

    }catch (ApplicationException aex) {
      throw aex;
    }catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(e.getMessage());       
    } finally {
      conn = null;
    }
  }

  public void deleteRecord2(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {

    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    DmsDocument document = (DmsDocument) documentForm.getFormData();
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);

    try {
      document.setDocumentDetails(docRetrievalManager.retrievalDocumentDetailsList(request));
    } catch (Exception ee) {
      log.error("Cannot set document details", ee);
    }

    if (document.getID() != null) {
      if (DmsDocument.DOCUMENT_TYPE.equals(document.getDocumentType())) {
        docOperationManager.deleteDocument(document);
      } else {
        docOperationManager.deleteFolder(document);
      }
    }

    sessionContainer = null;
    conn = null;
    docRetrievalManager.release();
    docOperationManager.release();
  }
  
  /**
   * joan.xiong add code for bug EIP-68 to delete item.2006/10/12
   * 
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     void
   *  @throws     ApplicationException  Throws ApplicationException the deleteion failed
   */
  
  public void deleteRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
	  MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
	  DmsDocument document = (DmsDocument) documentForm.getFormData();
	  SessionContainer sessionContainer = this.getSessionContainer(request);
	  Connection conn = this.getConnection(request);
	  DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
	  DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
	  DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
	  DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
	  ApplicationContainer container = (ApplicationContainer)request.getSession().getServletContext().getAttribute(GlobalConstant.APPLICATION_CONTAINER_KEY);
	  
	  /*
	   * joan.xiong update code for bug EIP-213 by 2006/11/09
	   */
//	  boolean isIgnoreDeleteShortcut = request.getParameter("ignoreDeleteShortcut").equals("true")?true:false;
	  boolean isIgnoreDeleteShortcut;
	  if(Utility.isEmpty(request.getParameter("ignoreDeleteShortcut"))){
		  isIgnoreDeleteShortcut = false;
	  }else{
		  isIgnoreDeleteShortcut = request.getParameter("ignoreDeleteShortcut").equals("true")?true:false;
	  }
	  /*
	   * joan.xiong update code end
	   */
	  //step 1: validate tree node, add id to lstIdHasRight/lstIdMisRight/lstIdBeLocked
      DmsDocument sourceDocument = (DmsDocument)dmsDocumentDAO.getObjectByID(document.getID());
      DmsValidation validation = docValidateManager.validateDeleteAction(sourceDocument, isIgnoreDeleteShortcut);
      //step 2: begin delete documents
      String cacheKey = "D"+sessionContainer.getSessionID()+""+System.currentTimeMillis();
	  try{
		  List deleteDocumentIds = validation.getLstIdAccept();
		  //step 2.1: check and lock operation id to application cache
		  boolean success = container.checkAndLockDocumentOperationID(cacheKey, deleteDocumentIds, "ACDIMU");
	      if (!success) {
	    	  this.addError(request, "errors.dms.fail_to_delete", docRetrievalManager.getLocationPath(document.getID()));
	    	  this.addError(request, "errors.dms.cannot_edit_now");
	      }else {
	    	  //step 2.2: delete documents
	    	  docOperationManager.deleteDocument(sourceDocument, validation);
	    	  
	    	  //step 2.3: message throws
	          List lstIdHasRight = validation.getLstIdAccept();
	          List lstIdMisRight = validation.getLstIdReject();
	          List lstIdBeLocked = validation.getLstIdlocked();
	          List lstIdBeDeleted = validation.getLstIdDeleted();
	          List lstIdBeArchived = validation.getLstIdArchived();
	          List lstIdRelatedShortcut = validation.getLstIdHaveRelationship();
	          String locationPath = docRetrievalManager.getLocationPath(document.getID());
	          if (validation.isSuccess()) {
	            this.addMessage(request, "dms.message.document_deleted_success", locationPath, String.valueOf(lstIdHasRight.size()));
	          }else {
	            this.addError(request, "errors.dms.fail_to_delete", locationPath);
	            for (int i=0; i<lstIdMisRight.size(); i++) {
	              this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));                            
	            }
	            for (int i=0; i<lstIdBeLocked.size(); i++) {
	              this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));                            
	            }
	            for (int i=0; i<lstIdBeDeleted.size(); i++) {
	              this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));                            
	            }
	            for (int i=0; i<lstIdBeArchived.size(); i++) {
	              this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));                            
	            }
	            for (int i=0; i<lstIdRelatedShortcut.size(); i++) {
	              this.addError(request,"errors.dms.has_relationship",docRetrievalManager.getLocationPath((Integer)lstIdRelatedShortcut.get(i)));                            
	            }
	          }
	      }
	  }catch (ApplicationException ex) {
        throw ex;
      }catch (Exception ex) {
        throw new ApplicationException(ex);
      }finally {
        container.unlockDmsDocumentOperationID(cacheKey);
      }
      conn = null;
      sessionContainer = null;
      container = null;
      docValidateManager.release();
      docOperationManager.release();
      docRetrievalManager.release();
  }

  
  /**
   * Copy record(s).
   * lee add in 06/06/21, replace top method copyRecord.
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public boolean copyRecord2(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentValidateManager  docValidateManager  = new DocumentValidateManager(sessionContainer, conn);
    boolean copySuccessed = false;
    DmsDocument newTmpDocument = null;
    
    //step 1: get setting data from submit
    Integer sourceID = documentForm.getID() != null ? new Integer(documentForm.getID()) : null;
    Integer destinID = documentForm.getDestinationID() != null ? new Integer(documentForm.getDestinationID()) : null;
    DmsDocument sourceDocument = docRetrievalManager.getDocument(sourceID);
    DmsDocument destinDocument = docRetrievalManager.getDocument(destinID);
    DmsDocument newDmsDocument = new DmsDocument();
    newDmsDocument.setDocumentName(documentForm.getDocumentName());
    newDmsDocument.setReferenceNo(documentForm.getReferenceNo());
    newDmsDocument.setDescription(documentForm.getDescription());
    newDmsDocument.setUserDef1(documentForm.getUserDef1());
    newDmsDocument.setUserDef2(documentForm.getUserDef2());
    newDmsDocument.setUserDef3(documentForm.getUserDef3());
    newDmsDocument.setUserDef4(documentForm.getUserDef4());
    newDmsDocument.setUserDef5(documentForm.getUserDef5());
    newDmsDocument.setUserDef6(documentForm.getUserDef6());
    newDmsDocument.setUserDef7(documentForm.getUserDef7());
    newDmsDocument.setUserDef8(documentForm.getUserDef8());
    newDmsDocument.setUserDef9(documentForm.getUserDef9());
    newDmsDocument.setUserDef10(documentForm.getUserDef10());
    if(!Utility.isEmpty(documentForm.getUserDefinedFieldID())){
      newDmsDocument.setUserDefinedFieldID(TextUtility.parseIntegerObj(documentForm.getUserDefinedFieldID()));
      newDmsDocument.setDocumentDetails(docRetrievalManager.retrievalDocumentDetailsList(request));
    }
    boolean[] options = new boolean[4];
    options[0] = (GlobalConstant.TRUE.equals(documentForm.getSubmitSystemWorkflow()) && !Utility.isEmpty(documentForm.getWorkflowRecordID())) ? true : false;
    options[1] = DmsOperationConstant.COPY_OPERATION_AS_NEW.equals(documentForm.getCopyFileOpt());
    options[2] = DmsOperationConstant.COPY_ALL_VERSIONS.equals(documentForm.getCopyVersionOpt());
    options[3] = DmsOperationConstant.COPY_STRUCTURE_ONLY.equals(documentForm.getCopyStructureOnly());
    
    String oriPath = docRetrievalManager.getLocationPath(sourceDocument.getParentID());
    request.setAttribute("oriPath",oriPath);
      //step 2: validate copy action
      DmsValidation validation = docValidateManager.validateCopyAction(sourceDocument, destinDocument, newDmsDocument, options);
      if (!validation.isSuccess()) { 
        //step 3.1: fail to validate, add error message
        this.addError(request, "errors.dms.fail_to_copy", docRetrievalManager.getLocationPath(sourceID));
        if (validation.isInvalidName()) {
          String sysInvalidCharacters = SystemParameterFactory.getSystemParameter(SystemParameterConstant.INVALID_CHARACTER);
          addError(request, "errors.framework.character_error", sysInvalidCharacters);
        }else if (validation.isDuplicateName()) {
          addError(request, "errors.dms.duplicate_document_name");
        }else if (validation.isUnderSameNode()) {
          addError(request, "errors.dms.location_under_same_node");
        }else if (validation.isNotEnoughDiskSpace()) {
          addError(request, "errors.dms.not_enough_disk_space", String.valueOf(validation.getDiskSpaceFree()), String.valueOf(validation.getDiskSpaceRequire()));
        }else if (validation.isNotEnoughStorageSpace()) {
          addError(request, "errors.dms.no_available_space");
        }else if (validation.isCantCreateShortcut()){
          addError(request, "dms.message.unable_shortcut_personal_to_public");
        }else {
          if (!validation.getLstIdReject().isEmpty()) {
            List lstIdReject = validation.getLstIdReject();
            for (int i=0; i<lstIdReject.size(); i++) {
              addError(request, "errors.dms.no_permission", docRetrievalManager.getLocationPath((Integer)lstIdReject.get(i)));
            }
          }
          if (!validation.getLstIdlocked().isEmpty()) {
            List lstIdLocked = validation.getLstIdlocked();
            for (int i=0; i<lstIdLocked.size(); i++) {
              addError(request, "errors.dms.been_checkout", docRetrievalManager.getLocationPath((Integer)lstIdLocked.get(i)));
            }
          }
          if(!validation.getLstIdHaveRelationship().isEmpty()){
            List lstIdHaveRelationShip = validation.getLstIdHaveRelationship();
            for(int i=0;i<lstIdHaveRelationShip.size();i++){
              addError(request,"errors.dms.shortcut_copy_in_public",docRetrievalManager.getDocumentByID((Integer)lstIdHaveRelationShip.get(i)).getDocumentName());
            }
          }
        }
      }else { 
        //3.2: validation success, copy documents begin...
        ApplicationContainer container = (ApplicationContainer)request.getSession().getServletContext().getAttribute(GlobalConstant.APPLICATION_CONTAINER_KEY);
        String cacheKey = "C"+sessionContainer.getSessionID()+""+System.currentTimeMillis();
        try {
          //3.2.1: check and lock operation id to application cache
          boolean success = container.checkAndLockDocumentOperationID(cacheKey, validation.getLstIdAccept(), "ACDMU");
          if (!success) {
            this.addError(request, "errors.dms.fail_to_copy", docRetrievalManager.getLocationPath(sourceID));
            this.addError(request, "errors.dms.cannot_edit_now");
          }else {
            //3.2.2: copy documents in batch
            newTmpDocument = docOperationManager.copyDocument(sourceDocument, destinDocument, newDmsDocument, validation, options);
            copySuccessed = true;
            //joan.xiong update code for bug EIP-1224 by 2006/12/20  copy sourcedoc permission to targetdoc
            if(copySuccessed){
                com.dcivision.user.dao.UserPermissionInheritDAObject userPermInheritDAO = new com.dcivision.user.dao.UserPermissionInheritDAObject(this.getSessionContainer(request), this.getConnection(request));
                if(Utility.isEmpty(userPermInheritDAO.getObjectByObjectTypeObjectID(sourceDocument.getDocumentType(),sourceDocument.getID()))){
                	documentForm.setInheritanceFlag(GlobalConstant.TRUE);
                }
                documentForm.setObjectID(sourceDocument.getID().toString());
                this.selectPermissionObjects(mapping,documentForm,request,response);
                String permData = TextUtility.replaceString(documentForm.getAllPermissionData(), "\r", "");
                String[] tmpAry = TextUtility.splitString(permData, "\n");
                String tempPermission = "";
                if(!Utility.isEmpty(tmpAry)){
                    for(int t=0;t<tmpAry.length;t++){
                    	String[] rowAry = TextUtility.splitString(tmpAry[t], "\t");
                    	rowAry[7] = "-1";
                    	for(int m=0;m<rowAry.length;m++){
                    		tempPermission += rowAry[m]+"\t";
                    	}
                    	tempPermission +="\n";
                    }
                }
                documentForm.setAllPermissionData(tempPermission);
                documentForm.setObjectID(newTmpDocument.getID().toString());
                this.updateInheritanceFlag(mapping,documentForm,request,response);
                this.updatePermissionSetting(form,sessionContainer,conn,newTmpDocument.getID());
                this.selectPermissionObjects(mapping,documentForm,request,response);
            }
            //joan.xiong update code end
            this.addMessage(request, "dms.message.document_copy_success", docRetrievalManager.getLocationPath(sourceID), String.valueOf(validation.getLstIdAccept().size()));
          }
        }catch (ApplicationException ex) {
          throw ex;
        }finally {
          container.unlockDmsDocumentOperationID(cacheKey);
          container = null;
        }
      }
    
    //step 3: old process
    DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(TextUtility.parseIntegerObj(documentForm.getRootID()));
    request.setAttribute("rootFolder", documentRoot);
    String path = docRetrievalManager.getLocationPath(destinDocument.getID());
    request.setAttribute("location", path);
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    List publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
    request.setAttribute("publicRootList", publicRootList);
    rootRetrievalManager.release();

    sessionContainer = null;
    conn = null;
    docValidateManager.release();
    docOperationManager.release();
    docRetrievalManager.release();
    
    if(copySuccessed && !DmsOperationConstant.COPY_MORE_OPERATION.equals(documentForm.getOpMode())){
    	documentForm.setID(newTmpDocument.getID().toString());//Update By Jim.Zhou		2006/08/31		Bug:EIP-116
    }
    
    return copySuccessed;
  }

  public void moveRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    log.debug("Moveing  document ...");
    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    Integer sourceID = documentForm.getID() != null ? new Integer(documentForm.getID()) : null;
    Integer destinationID = documentForm.getDestinationID() != null ? new Integer(documentForm.getDestinationID()) : null;
    Integer targetRootID = documentForm.getTargetRootID() != null ? new Integer(documentForm.getTargetRootID()) : null;
    log.debug("sourceID: " + sourceID + " destinationID: " + destinationID + " tagetRootID = " + targetRootID);
    log.debug("moving document name = " + documentForm.getDocumentName());

    DmsDocument sourceDocument = docRetrievalManager.getDocument(sourceID);
    DmsDocument oldSourceDocument=docRetrievalManager.getDocument(sourceID);
    Integer oldParentID=oldSourceDocument.getParentID();
   
    //Update the new document name
    sourceDocument.setDocumentName(documentForm.getDocumentName());
    oldSourceDocument.setDocumentName(documentForm.getDocumentName());
    oldSourceDocument.setReferenceNo(documentForm.getReferenceNo());
    oldSourceDocument.setDescription(documentForm.getDescription());
    
    if(documentForm.getDestinationPath().indexOf("PERSONAL")>=0){
      oldSourceDocument.setEffectiveEndDate(TextUtility.parseTimestamp(""));
    }
    // get the destination file
    DmsDocument destinationDoc = docRetrievalManager.getDocument(destinationID);

    /* Validation Rule */
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
    docValidateManager.checkHasPermissionOnObject(GlobalConstant.OBJECT_TYPE_DOCUMENT, destinationDoc.getID(), destinationDoc.getRootID(), "I");
    log.debug(".................................Has permission on target folder");
    if (DmsDocument.FOLDER_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.COMPOUND_DOC_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.PAPER_DOC_TYPE.equals(sourceDocument.getDocumentType())
        || DmsDocument.EMAIL_DOC_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.FLOW_DOC_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.FORM_DOC_TYPE.equals(sourceDocument.getDocumentType())){
      //check the same node
      docValidateManager.checkUnderSameNode(sourceDocument, destinationDoc);
      // check duplicate name of same level if config file defined
      sourceDocument.setParentID(destinationDoc.getID());
      sourceDocument.setRootID(destinationDoc.getRootID());
      if(DmsDocument.COMPOUND_DOC_TYPE.equals(destinationDoc.getDocumentType())){
        if(DmsDocument.FOLDER_TYPE.equals(sourceDocument.getDocumentType())){
          throw new ApplicationException(DmsErrorConstant.FOLDER_COPY_COMPOUND_DOC,null,"moved"); 
        }else if(DmsDocument.COMPOUND_DOC_TYPE.equals(sourceDocument.getDocumentType())){
          throw new ApplicationException(DmsErrorConstant.COMPOUND_DOC_COPY_COMPOUND_DOC,null,"moved"); 
        }else if(DmsDocument.PAPER_DOC_TYPE.equals(sourceDocument.getDocumentType())){
          throw new ApplicationException(DmsErrorConstant.PAPER_DOC_COPY_COMPOUND_DOC, null,"moved");   
        }
      }else if(DmsDocument.PAPER_DOC_TYPE.equals(destinationDoc.getDocumentType())){
        if(DmsDocument.FOLDER_TYPE.equals(sourceDocument.getDocumentType())){
          throw new ApplicationException(DmsErrorConstant.FOLDER_COPY_PAPER_DOC,null,"moved"); 
        }else if(DmsDocument.COMPOUND_DOC_TYPE.equals(sourceDocument.getDocumentType())){
          throw new ApplicationException(DmsErrorConstant.COMPOUND_DOC_COPY_PAPER_DOC,null,"moved"); 
        }else if(DmsDocument.PAPER_DOC_TYPE.equals(sourceDocument.getDocumentType())){
          throw new ApplicationException(DmsErrorConstant.PAPER_DOC_COPY_PAPER_DOC,null,"moved");   
        } 
      }
      docValidateManager.checkDuplicateNameSupport(sourceDocument);
      log.debug("No duplicate name exists");
    }

    boolean bDocumentActive = true;
    if (GlobalConstant.TRUE.equals(((MaintDmsDocumentForm)form).getSubmitSystemWorkflow()) && !Utility.isEmpty(((MaintDmsDocumentForm)form).getWorkflowRecordID())) {
      bDocumentActive = false;
    }
    
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    List tempDocumentList = dmsDocumentDAO.getAllChildListByParentIDRootID(oldSourceDocument.getID()); //using original root id
    boolean isMoveFlag = true;
    
    //check permission and checkout
    PermissionManager permManager = sessionContainer.getPermissionManager();
    DmsRootDAObject dmsRootDAObject = new DmsRootDAObject(sessionContainer,conn);
    DmsRoot dmsRoot = (DmsRoot)dmsRootDAObject.getObjectByID(oldSourceDocument.getRootID());
    //List documentList = new ArrayList();
    if (!Utility.isEmpty(tempDocumentList)) {
      if (!DmsRoot.PERSONAL_ROOT.equals(dmsRoot.getRootType())) {
        for (int i = 0; i < tempDocumentList.size(); i++) {
          DmsDocument subDocument = (DmsDocument) tempDocumentList.get(i);
          if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(subDocument.getRecordStatus()) || GlobalConstant.RECORD_PENDING.equals(subDocument.getRecordStatus())) {
            if (!permManager.hasAccessRight(conn,DmsDocument.DOCUMENT_TYPE,subDocument.getID(),WebdavOperationManager.DMS_PERMISSION_MOVE_CODE) || GlobalConstant.STATUS_LOCKED.equals(subDocument.getItemStatus())){
              isMoveFlag = false;
              break;
            }
          }
        }
      }
    }
    
    
    
    log.debug("submit system workflow: "+((MaintDmsDocumentForm)form).getSubmitSystemWorkflow()+", workflow record id: "+((MaintDmsDocumentForm)form).getWorkflowRecordID() +", document status: "+bDocumentActive);
    if (DmsDocument.FOLDER_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.COMPOUND_DOC_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.PAPER_DOC_TYPE.equals(sourceDocument.getDocumentType())
          || DmsDocument.EMAIL_DOC_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.FLOW_DOC_TYPE.equals(sourceDocument.getDocumentType()) || DmsDocument.FORM_DOC_TYPE.equals(sourceDocument.getDocumentType())) {
      if (isMoveFlag){
        docOperationManager.moveFolder(oldSourceDocument, destinationDoc, targetRootID, bDocumentActive);
      }else{
        throw new ApplicationException(DmsErrorConstant.DMS_MESSAGE_CANNOT_MOVE_SUM_DOCUMENT);
      }
    } else {
      docOperationManager.moveDocument(oldSourceDocument, destinationDoc, targetRootID, false, bDocumentActive);
    }
    documentForm.setParentID(destinationDoc.getParentID().toString());
    documentForm.setRootID(destinationDoc.getRootID().toString());
    DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(TextUtility.parseIntegerObj(documentForm.getRootID()));
    request.setAttribute("rootFolder", documentRoot);

    // Refresh the permission cache in order to make sure the access right is correct.
    String path = docRetrievalManager.getLocationPath(destinationID);
    request.setAttribute("location", path);

    // Retrieve the folder list for folder tree listing.
    List folderTreeList = docRetrievalManager.getFolderByParentIDRootID(documentRoot.getID(), new Integer(documentForm.getRootID()));
    request.setAttribute("folderTreeList", folderTreeList);

    // Retrieve the accessible public root list.
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    List publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
    request.setAttribute("publicRootList", publicRootList);
    request.setAttribute("oldParentID", oldParentID);

    // Release resources.
    sessionContainer = null;
    conn=null;
    docRetrievalManager.release();
    docOperationManager.release();

  }
  
  public boolean moveRecord2(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentValidateManager  docValidateManager  = new DocumentValidateManager(sessionContainer, conn);
    
    Integer sourceID = documentForm.getID() != null ? new Integer(documentForm.getID()) : null;
    Integer destinID = documentForm.getDestinationID() != null ? new Integer(documentForm.getDestinationID()) : null;
    DmsDocument sourceDocument = docRetrievalManager.getDocument(sourceID);
    DmsDocument destinDocument = docRetrievalManager.getDocument(destinID);
    DmsDocument newDmsDocument = new DmsDocument();
    newDmsDocument.setDocumentName(documentForm.getDocumentName());
    newDmsDocument.setReferenceNo(documentForm.getReferenceNo());
    newDmsDocument.setDescription(documentForm.getDescription());
    boolean isByWorkFlow = (GlobalConstant.TRUE.equals(documentForm.getSubmitSystemWorkflow()) && !Utility.isEmpty(documentForm.getWorkflowRecordID())) ? true : false;
    boolean moveSuccessed = false;  
    String oriPath = docRetrievalManager.getLocationPath(sourceDocument.getParentID());
    request.setAttribute("oriPath",oriPath);
    
      //step 1: validate move action
      DmsValidation validation = docValidateManager.validateMoveAction(sourceDocument, destinDocument, newDmsDocument);
      
      //step 2: begin move documents
      if (!validation.isSuccess()) { //2.1: fail to validate, add error message and throw exception 
        //Add By Jim.Zhou		2006/07/14		Bug #5006
      	//Add End
        if (validation.isInvalidName()) {
          String sysInvalidCharacters = SystemParameterFactory.getSystemParameter(SystemParameterConstant.INVALID_CHARACTER);
          addError(request, "errors.framework.character_error", sysInvalidCharacters);
        }else if (validation.isDuplicateName()) {
          addError(request, "errors.dms.duplicate_document_name");
        }else if (validation.isUnderSameNode()) {
          addError(request, "errors.dms.location_under_same_node");
        }else if (validation.isNotEnoughDiskSpace()) {
          addError(request, "errors.dms.not_enough_disk_space", String.valueOf(validation.getDiskSpaceFree()), String.valueOf(validation.getDiskSpaceRequire()));
        }else if (validation.isNotEnoughStorageSpace()) {
          addError(request, "errors.dms.no_available_space");
        }else if (validation.isCantCreateShortcut()){
          addError(request, "dms.message.unable_shortcut_personal_to_public");
        }else {
          if (!validation.getLstIdReject().isEmpty()) {
            List lstIdReject = validation.getLstIdReject();
            for (int i=0; i<lstIdReject.size(); i++) {
              addError(request, "errors.dms.no_permission", docRetrievalManager.getLocationPath((Integer)lstIdReject.get(i)));
            }
          }
          if (!validation.getLstIdlocked().isEmpty()) {
            List lstIdLocked = validation.getLstIdlocked();
            for (int i=0; i<lstIdLocked.size(); i++) {
              addError(request, "errors.dms.been_checkout", docRetrievalManager.getLocationPath((Integer)lstIdLocked.get(i)));
            }
          }
          if (!validation.getLstIdArchived().isEmpty()) {
            List lstIdArchived = validation.getLstIdArchived();
            for (int i=0; i<lstIdArchived.size(); i++) {
              addError(request, "errors.dms.been_archived", docRetrievalManager.getLocationPath((Integer)lstIdArchived.get(i)));
            }
          }
          if(!validation.getLstIdHaveRelationship().isEmpty()){
            List lstIdHaveRelationShip = validation.getLstIdHaveRelationship();
            for(int i=0;i<lstIdHaveRelationShip.size();i++){
              addError(request,"errors.dms.shortcut_in_public",docRetrievalManager.getDocumentByID((Integer)lstIdHaveRelationShip.get(i)).getDocumentName());
            }
          }
        }
      }else { //2.2: validation success, copy documents begin...
        ApplicationContainer container = (ApplicationContainer)request.getSession().getServletContext().getAttribute(GlobalConstant.APPLICATION_CONTAINER_KEY);
        String cacheKey = "M"+sessionContainer.getSessionID()+""+System.currentTimeMillis();
        try {
          //2.2.1: check and lock operation id to application cache
          boolean success = container.checkAndLockDocumentOperationID(cacheKey, validation.getLstIdAccept(), "ACDIMU");
          if (!success) {
            this.addError(request, "errors.dms.fail_to_move", docRetrievalManager.getLocationPath(sourceID));
            this.addError(request, "errors.dms.cannot_edit_now");
          }else {
            //2.2.2: begin move documents
            docOperationManager.moveDocument(sourceDocument, destinDocument, newDmsDocument, validation, isByWorkFlow);
            moveSuccessed = true;
            this.addMessage(request, "dms.message.document_move_success", docRetrievalManager.getLocationPath(sourceID),  String.valueOf(validation.getLstIdAccept().size()));
          }
        }catch (ApplicationException ex) {
          this.addError(request,"errors.dms.fail_to_move",sourceDocument.getDocumentName());
          try {conn.rollback();}catch(Exception ignore) {log.error(ignore);}
        }finally {
          container.unlockDmsDocumentOperationID(cacheKey);
          container = null;
        }
      }
    
    //step 3: old process
    DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(TextUtility.parseIntegerObj(documentForm.getRootID()));
    request.setAttribute("rootFolder", documentRoot);
    String path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(parentID));
    request.setAttribute("location", path);
    // Retrieve the accessible public root list.
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    List publicRootList = rootRetrievalManager.getAllAccessibleRootsList();
    request.setAttribute("publicRootList", publicRootList);
    rootRetrievalManager.release();

    sessionContainer = null;
    conn = null;
    docValidateManager.release();
    docOperationManager.release();
    docRetrievalManager.release();
    
    return moveSuccessed;
  }

  public void refreshFormData(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    DmsDocument document = (DmsDocument) documentForm.getFormData();
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);

    documentForm.setFormData(document);
    if (!Utility.isEmpty(request.getParameter("uploadFile"))){
      documentForm.setDocumentName(request.getParameter("uploadFile"));
    }else{
      documentForm.setDocumentName(request.getParameter("documentName"));
    }
    List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(documentForm.getUserDefinedFieldID()));
    documentForm.setUdfDetailList(udfDetailList);
    String path = (String)request.getAttribute("location");
    if (Utility.isEmpty(path)) {
      path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(documentForm.getParentID()));
    }
    request.setAttribute("location", path);

    sessionContainer = null;
    conn=null;
    docRetrievalManager.release();
  }

  public void renameRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    
    //set the docDetailList and userDefinedFieldID
    DmsDocument document =(DmsDocument)documentForm.getFormData();
    DmsDocumentDetailDAObject dmsDocumentDetailDAObj = new DmsDocumentDetailDAObject(sessionContainer,conn);
    Integer documentID = TextUtility.parseIntegerObj(documentForm.getID());
    
    List docDetailList =dmsDocumentDetailDAObj.getListByDocumentID(documentID);
    if(!Utility.isEmpty(docDetailList)){
      DmsDocumentDetail tmpDmsDocumentDetail =(DmsDocumentDetail)docDetailList.get(0);
      Integer userDefinedFieldID = tmpDmsDocumentDetail.getUserDefinedFieldID();
      document.setDocumentDetails(docDetailList);
      document.setUserDefinedFieldID(userDefinedFieldID);
    }

    if (Utility.isEmpty(documentForm.getDocumentName()) || "".equals(documentForm.getDocumentName().trim())){
      if (DmsDocument.FOLDER_TYPE.equals(documentForm.getDocumentType())) {
        throw new EmptyContentException(DmsErrorConstant.EMPTY_FOLDER_NAME);
      }else{
        throw new EmptyContentException(DmsErrorConstant.EMPTY_DOCUMENT_NAME);
      }
    }
    DmsDocument newDocument  = docOperationManager.renameRecord(document);
    documentForm.setFormData(newDocument);

    sessionContainer = null;
    conn = null;
    docOperationManager.release();

  }

  public List parseUploadedUDFIndex(java.io.InputStream infile, HttpServletRequest request) throws Exception {
    List scanDocDetailList = new ArrayList();
    log.debug("Get Infile:" + infile.toString());

    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    // Create an Document node as the root for the output.
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
    org.w3c.dom.Document indexFile = docBuilder.parse(infile);
    //Get Class for USer Defined Type
    if (indexFile == null){
      log.debug("Cannot get .tif input stream ");
    }
    if (indexFile != null){
      log.debug("    Uploaded Index Set File Received");
      String udfClass = "";
      NodeList nl = indexFile.getElementsByTagName("document_profile");
      for (int i=0; i<nl.getLength(); i++){
        Element targetNode = (Element)nl.item(i);
        udfClass = targetNode.getAttribute("name");
      }
      //Classify the uploaded udf creation using prefix setting
      scannedUDFName = udfClass;
      if ("true".equals(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_SCAN_UDF_PREFIX_USE)))  {
        scannedUDFName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_SCAN_UDF_PREFIX) + udfClass;
      }

      //Parse the UDF and UDF Details from XML file
      Map udfMap = parseUserDefinedField(indexFile);

      scanDocDetailList = docOperationManager.createUploadedDocumentUDF(udfMap, indexFile);
    }

    infile.close();
    sessionContainer = null;
    conn = null;
    docOperationManager.release();

    return scanDocDetailList;
  }

  protected Map parseUserDefinedField (org.w3c.dom.Document indexFile) throws Exception{
    SysUserDefinedIndex sysUserDefinedIndex = new SysUserDefinedIndex();

    Map udfMap = new HashMap();

    //If new Class ->  new User Defiend Type
    String tmpClass="";
    NodeList nl = indexFile.getElementsByTagName("document_profile");
    for (int i=0; i<nl.getLength(); i++) {
      Element targetNode = (Element)nl.item(i);
      tmpClass = targetNode.getAttribute("name");
    }
    sysUserDefinedIndex.setUserDefinedType(scannedUDFName);
    sysUserDefinedIndex.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
    sysUserDefinedIndex.setDescription("");
    sysUserDefinedIndex.setImportType(SysUserDefinedIndex.IMPORT_TYPE);
    sysUserDefinedIndex.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
    sysUserDefinedIndex.setCreatorID(new Integer(0));
    //SysUserDefinedIndex = (SysUserDefinedIndex) userDefinedIndexDAO.insertObject(tmpSysUserDefinedIndex);
    udfMap.put("SysUserDefinedIndex", sysUserDefinedIndex);

    //New User Defined Field Details
    NodeList fieldList = indexFile.getElementsByTagName("field");
    List udfDetailList = new ArrayList();
    for (int i=0; i<fieldList.getLength(); i++){
      log.debug("UDF Detail size " + fieldList.getLength());
      Element targetNode = (Element)fieldList.item(i);
      String tmpField = targetNode.getAttribute("name");
      log.debug("UDF Detail Name = "+i+ " " + tmpField);

      SysUserDefinedIndexDetail tmpSysUserDefinedIndexDetail = new SysUserDefinedIndexDetail();
      tmpSysUserDefinedIndexDetail.setUserDefinedID(sysUserDefinedIndex.getID());
      tmpSysUserDefinedIndexDetail.setFieldName(tmpField.trim());
      tmpSysUserDefinedIndexDetail.setMandatory(new String("N"));
      //get the text as subnode handling
      Node subnode = fieldList.item(i).getFirstChild();
      String fieldValue = "";
      if (subnode!=null) {
        fieldValue = subnode.getNodeValue();
        log.debug("value " + subnode.getNodeValue());
      }
      String tmpFieldType = targetNode.getAttribute("type");
      log.debug("UDF Detail Type = "+ tmpFieldType);
      if (!Utility.isEmpty(tmpFieldType)) {
        tmpSysUserDefinedIndexDetail.setFieldType(tmpFieldType);
      } else {
        tmpSysUserDefinedIndexDetail.setFieldType(SysUserDefinedIndexDetail.STRING_FIELD);
      }
      tmpSysUserDefinedIndexDetail.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
      tmpSysUserDefinedIndexDetail.setCreatorID(new Integer(0));
      udfDetailList.add(tmpSysUserDefinedIndexDetail);
    }
    udfMap.put("udfDetailList", udfDetailList);

    return udfMap;
  }

  public void executeWorkflowRoutine(ActionMapping mapping, WorkflowActionFormInterface form, HttpServletRequest request, HttpServletResponse response, String opMode, String navMode) throws ApplicationException {
    log.info("########## MaintDmsDocumentDocumentAction Workflow Routine Begin ##########");
    MaintDmsDocumentForm dmsDocumentForm = (MaintDmsDocumentForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DmsDocumentDAObject dmsDocDAO = new DmsDocumentDAObject(sessionContainer, conn);
    WorkflowRecordDAObject workflowRecordDAO=new WorkflowRecordDAObject(sessionContainer,conn);
    Integer objID = TextUtility.parseIntegerObj(((com.dcivision.framework.web.AbstractActionForm)form).getID());
    DmsDocument dmsDocument=(DmsDocument)dmsDocDAO.getObjectByID(objID);
    
    String wfRecordIDs = form.getWorkflowRecordID();
    if(wfRecordIDs.indexOf("|") > 0){
      wfRecordIDs = wfRecordIDs.substring(0,wfRecordIDs.indexOf("|"));  
    }
    Integer workflowRecordID=TextUtility.parseIntegerObj(wfRecordIDs);
    
    WorkflowRecord workflowRecord=(WorkflowRecord)workflowRecordDAO.getObjectByID(workflowRecordID);
    String categoryID=workflowRecord.getWorkflowCategoryID().toString();
    
    if (GlobalConstant.TRUE.equals(form.getSubmitSystemWorkflow()) && !Utility.isEmpty(form.getWorkflowRecordID())) {
      if (GlobalConstant.OP_MODE_INSERT.equals(opMode) || GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode) ) {
        if(!(DmsDocument.PAPER_DOC_TYPE.equals(dmsDocument.getDocumentType()) && (SystemWorkflowConstant.DMS_CREATE_PAPER_DOCUMENT.equals(categoryID) || SystemWorkflowConstant.DMS_CREATE_PAPER_UDF_DOCUMENT.equals(categoryID)))){
          dmsDocDAO.updateStatusByObjectID(objID,GlobalConstant.RECORD_PENDING);
          dmsDocumentForm.setRecordStatus(GlobalConstant.RECORD_PENDING);
        }
      }
    }
    dmsDocDAO=null;
    conn=null;
    log.info("########## MaintDmsDocumentDocumentAction Workflow Routine End   ##########");
  }

  public String setDefaultProfileValue(List defaultProfileList, String targetValue, int targetPos){
    String convertedValue = targetValue;
    targetPos--;  //to get the correct pos in list
    if (!Utility.isEmpty(targetValue)) {
    // Default profile display.

      DmsDefaultProfileSetting setting = ( (DmsDefaultProfileSetting) defaultProfileList.get(targetPos));
      if (DmsDefaultProfileSetting.FIELD_TYPE_INTEGER.equals(setting.getFieldType())) {
        Integer tmpValue = TextUtility.parseIntegerObj(targetValue);
        convertedValue = tmpValue.toString();

      } else if (DmsDefaultProfileSetting.FIELD_TYPE_FLOAT.equals(setting.getFieldType())) {
        Float tmpValue = TextUtility.parseFloatObj(targetValue);
        convertedValue = tmpValue.toString();

      } else if (DmsDefaultProfileSetting.FIELD_TYPE_DATE.equals(setting.getFieldType())) {
        String scanDateFormat = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_SCAN_DATE_FORMAT);
        java.sql.Timestamp date = Utility.parseDateStringToSystemDate(targetValue, scanDateFormat);
        if (date!=null){
         convertedValue=date.toString();
        }
      } else if (DmsDefaultProfileSetting.FIELD_TYPE_STRING.equals(setting.getFieldType())) {
      } else if (DmsDefaultProfileSetting.FIELD_TYPE_SELECT_DATABASE.equals(setting.getFieldType())
                 || DmsDefaultProfileSetting.FIELD_TYPE_SELECT_HARDCODE.equals(setting.getFieldType())) {
      }
    }
    return convertedValue;
  }
  
  
  public void getPaperDocByRefNo(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);

    Integer documentID = TextUtility.parseIntegerObj(form.getID());
    DmsDocument document = docRetrievalManager.getDocumentByDocTypeRefNo(DmsDocument.PAPER_DOC_TYPE, ((MaintDmsDocumentForm) form).getReferenceNo());
    
    if(document != null){
      form.setID(document.getID().toString());
    }else{
      throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
    }
     
      sessionContainer = null;
      conn = null;
      docRetrievalManager.release();
  }
 
  public void insertReminderNotification(SessionContainer sessionContainer, Connection conn,DmsDocument document) throws ApplicationException  {
    String notificationWay ="";
    UpdateAlert updateAlert = new UpdateAlert();
    updateAlert.setObjectType(UpdateAlert.DOCUMENT_TYPE);
    updateAlert.setObjectID(document.getID());
    AlertManager alertManager = new AlertManager(sessionContainer, conn);
    
    notificationWay = TextUtility.join(notificationWay, document.getNotificationWay());
    Timestamp targetSrcTime = document.getEffectiveEndDate();
    String reminderType = document.getReminderType();
//    int reminderAmount = document.getReminderAmount().intValue();
    Integer versionID = document.getVersionID();
    
    UpdateAlert newUpdateAlert=alertManager.createUpdateAlert(updateAlert, UpdateAlert.DOCUMENT_TYPE);

    UpdateAlertType updateAlertType = new UpdateAlertType();
    updateAlertType.setUpdateAlertID(newUpdateAlert.getID());
    updateAlertType.setActionType(UpdateAlert.REMIND_ACTION);
    updateAlertType.setNotifyWay(notificationWay);
    updateAlertType = alertManager.createAlertUpdateType(updateAlertType);

    UpdateAlertSystemLog updateAlertSystemLog = new UpdateAlertSystemLog();
    updateAlertSystemLog.setUpdateAlertTypeID(updateAlertType.getID());
    updateAlertSystemLog.setActionUserID(sessionContainer.getUserRecordID());
    updateAlertSystemLog.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
    updateAlertSystemLog.setRecordStatus(GlobalConstant.STATUS_INACTIVE);       
    
    updateAlertSystemLog.setActionDate(targetSrcTime);
    updateAlertSystemLog.setVersionID(versionID);
    updateAlertSystemLog = alertManager.createSystemLog(updateAlertSystemLog);

    MtmUpdateAlertRecipient recipient = new MtmUpdateAlertRecipient();
    recipient.setUpdateAlertID(newUpdateAlert.getID());
    recipient.setRecipientType(UpdateAlert.USER_RECIPIENT);
    recipient.setRecipientID(sessionContainer.getUserRecordID());
    alertManager.createUpdateAlertRecipient(newUpdateAlert, updateAlertType, recipient);
    
  }
  


  /** Parse the input */
  public void parseFormXmlDataToForm(MaintDmsDocumentForm form ) throws IOException, SAXException {
    try { // Get an efficient reader for the file
      String odmaProcess = "" ;
      String opMode = "" ;
      String navMode = "" ;
      String curFunctionCode = "" ;
      String closeFlag = "" ;
      String directPage = "" ;
      String documentID = "" ;
      String parentID = ""  ;
      String rootID = "" ;
      String checkinType = "" ;
      String referenceNo = ""  ;
      String description = "";     
      String trueFileName = "";
      String documentType = "";
      String createType = "" ;
      String priority = "" ;
      String clientType = "" ;
      
      InputStream inputStream = null;
      FormFile formFile = null;
      formFile = form.getFormFieldXmlFile();
      inputStream = formFile.getInputStream();
      InputSource input = new InputSource();
      input.setByteStream(inputStream);  
       
      
      // Create an Document node as the root for the output.
      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
      org.w3c.dom.Document indexFile = docBuilder.parse(input);

      /* Parse Document tag for the use name and login pwd */
      NodeList doclist = indexFile.getElementsByTagName("form");
      Node docNode = doclist.item(0);
      if (docNode != null) {
        if ("form".equals(docNode.getNodeName())) {
          try { odmaProcess = ((Element)docNode).getAttributeNode("odmaProcess").getValue(); } catch (Exception ignore) {}
          try { opMode = ((Element)docNode).getAttributeNode("opMode").getValue(); } catch (Exception ignore) {}
          try { navMode = ((Element)docNode).getAttributeNode("navMode").getValue(); } catch (Exception ignore) {}
          try { curFunctionCode = ((Element)docNode).getAttributeNode("curFunctionCode").getValue(); } catch (Exception ignore) {}
          try { closeFlag = ((Element)docNode).getAttributeNode("closeFlag").getValue(); } catch (Exception ignore) {}
          try { directPage = ((Element)docNode).getAttributeNode("directPage").getValue(); } catch (Exception ignore) {}
          try { documentID = ((Element)docNode).getAttributeNode("documentID").getValue(); } catch (Exception ignore) {}
          try { parentID = ((Element)docNode).getAttributeNode("parentID").getValue(); } catch (Exception ignore) {}
          try { rootID = ((Element)docNode).getAttributeNode("rootID").getValue(); } catch (Exception ignore) {}
          try { checkinType = ((Element)docNode).getAttributeNode("checkinType").getValue(); } catch (Exception ignore) {}
          try { referenceNo = ((Element)docNode).getAttributeNode("referenceNo").getValue(); } catch (Exception ignore) {}
          try { description = ((Element)docNode).getAttributeNode("description").getValue(); } catch (Exception ignore) {}
          try { documentType = ((Element)docNode).getAttributeNode("documentType").getValue(); } catch (Exception ignore) {}
          try { trueFileName = ((Element)docNode).getAttributeNode("trueFileName").getValue(); } catch (Exception ignore) {}          
          try { createType = ((Element)docNode).getAttributeNode("createType").getValue(); } catch (Exception ignore) {}
          try { priority = ((Element)docNode).getAttributeNode("priority").getValue(); } catch (Exception ignore) {}
          try { clientType = ((Element)docNode).getAttributeNode("clientType").getValue(); } catch (Exception ignore) {}          
          
          
          if(!"".equals(opMode)){
            form.setOpMode(opMode);
          }
          if(!"".equals(navMode)){
            form.setNavMode(navMode);
          }
          if(!"".equals(curFunctionCode)){
            form.setCurFunctionCode(curFunctionCode);
          }
          if(!"".equals(closeFlag)){
            form.setCloseFlag(closeFlag);
          }          
          if(!"".equals(createType)){
            form.setCreateType(createType);
          }
          if(!"".equals(priority)){
            form.setPriority(priority);
          }          
          if(!"".equals(documentType)){
            form.setDocumentType(documentType);
          }                    
          if(!"".equals(parentID)){
            form.setParentID(parentID);
          }
          if(!"".equals(rootID)){
            form.setRootID(rootID);
          }
          if(!"".equals(referenceNo)){
            form.setReferenceNo(referenceNo);
          }
          if(!"".equals(description)){
            form.setDescription(description);
          }
          if(!"".equals(trueFileName)){
            form.setTrueFileName(trueFileName);
          }
          if(!"".equals(clientType)){
            form.setClientType(clientType);
          }          
          
        }
      }
    } catch (Exception e) {
      log.error(e, e);
    } finally{
        //input.close();        
    }
  }
  
  /*
	 * function:this method the main function in order to get the zip file and
	 * save it change lotus server drag record to paradoc. author: barbin date:
	 * 2006-9-06 modify:
	 */

	public void parseFormZIPDataToForm(MaintDmsDocumentForm form) throws IOException {
		// Get an efficient reader for the file
		// get inputstream from post and save it to local server.
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_CACHEFOLDER_PATH);
			File catcheFolder = new File(path);
		    if (!catcheFolder.exists()) {
		       catcheFolder.mkdir();
		    }
			FormFile formFile = null;
			formFile = form.getFormFieldXmlFile();
			String baseDir = path + "/" + formFile.getFileName();
			form.setTrueFileName(formFile.getFileName());
			inputStream = formFile.getInputStream();
			File file = new File(baseDir);
			byte[] buf = new byte[1024];
			int readLen = 0;
			try {
				outputStream = new FileOutputStream(file);
				while ((readLen = inputStream.read(buf)) != -1) {
					outputStream.write(buf, 0, readLen);
				}
			} catch (Exception e) {
        log.error(e, e);
			}
		} catch (Exception e) {
      log.error(e, e);
		} finally {
			inputStream.close();
			outputStream.close();
		}
	}
  
 
  
  public void getParentFolderDefaultProfile(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);

    MaintDmsDocumentForm newForm = (MaintDmsDocumentForm) form;    
    
    //if action is new document view, get the parent folder's default profile
    if(!newForm.getClearIndex() && (Utility.isEmpty(form.getOpMode())|| GlobalConstant.OP_MODE_INSERT_NEW.equals(form.getOpMode())
            || DmsOperationConstant.COPY_OPERATION.equals(form.getOpMode()) || DmsOperationConstant.MOVE_OPERATION.equals(form.getOpMode()) || DmsOperationConstant.CREATE_EMPTY_FILE.equals(form.getOpMode()))
                        ){
        //List docDetailList = docRetrievalManager.getDocumentDetailList(documentID);
        DmsDocument parentProfileFolder = docRetrievalManager.getClosestHaveDefaultProfileFolder(TextUtility.parseIntegerObj(newForm.getParentID()));
        if (DmsOperationConstant.COPY_OPERATION.equals(form.getOpMode()) || DmsOperationConstant.MOVE_OPERATION.equals(form.getOpMode())){
            parentProfileFolder = docRetrievalManager.getClosestHaveDefaultProfileFolder(TextUtility.parseIntegerObj(newForm.getDestinationID()));
        }   
        if(!Utility.isEmpty(parentProfileFolder) && !newForm.getClearIndex()){
            List docDetailList = docRetrievalManager.getDocumentDetailList(parentProfileFolder.getID());
            if (docDetailList!=null&& docDetailList.size() > 0){
                //get the first one
                newForm.setUserDefinedFieldID(String.valueOf(((DmsDocumentDetail)docDetailList.get(0)).getUserDefinedFieldID()));
                newForm.setDocumentDetails(docDetailList);                
            }
            //  Use for List the target User Defined Fields Detail
            if (newForm.getUserDefinedFieldID() !=null){
                List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(newForm.getUserDefinedFieldID()));
                newForm.setUdfDetailList(udfDetailList);
            }
        }        
        return;
    }    
  
  }
  /**
   * getObjectType
   *
   * @return  The corresponding object type of permission setup action.
   */
  
  public String getObjectType() {
    return(GlobalConstant.OBJECT_TYPE_DOCUMENT);
  }
  
  /**
   * updateInheritanceFlag
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void updateInheritanceFlag(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;        
    boolean inheritFlag = GlobalConstant.TRUE.equals(actionForm.getInheritanceFlag());

    com.dcivision.user.dao.UserPermissionInheritDAObject userPermInheritDAO = new com.dcivision.user.dao.UserPermissionInheritDAObject(this.getSessionContainer(request), this.getConnection(request));

    if (inheritFlag) {
      userPermInheritDAO.deleteObjectByObjectTypeObjectID(actionForm.getObjectType(), new Integer(actionForm.getObjectID()));
    } else {
      com.dcivision.user.bean.UserPermissionInherit tmpUserPermissionInherit = new com.dcivision.user.bean.UserPermissionInherit();
      tmpUserPermissionInherit.setObjectType(GlobalConstant.OBJECT_TYPE_DOCUMENT);
      tmpUserPermissionInherit.setObjectID(new Integer(actionForm.getObjectID()));
      tmpUserPermissionInherit.setInheritanceFlag(GlobalConstant.FALSE);
      tmpUserPermissionInherit.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
      userPermInheritDAO.updateObject(tmpUserPermissionInherit);
    }
  }  
  
  public void insertMail(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
		SessionContainer sessionContainer = this.getSessionContainer(request);
		Connection conn = this.getConnection(request);
		MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;
    PermissionManager pm = sessionContainer.getPermissionManager();
		DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
		DmsRootDAObject dmsRootDAObject = new DmsRootDAObject(sessionContainer,conn);
		
		try {
			//parseFormXmlDataToForm(actionForm);			
			Integer destinationID = TextUtility.parseIntegerObj(actionForm.getParentID());
			DmsDocument destinationDoc = docRetrievalManager.getDocument(destinationID);
			DmsRoot dmsRoot = (DmsRoot)dmsRootDAObject.getObjectByID(destinationDoc.getRootID());
	        String dmsType=dmsRoot.getRootType();
	        String permission=pm.getPermission(conn,GlobalConstant.OBJECT_TYPE_DOCUMENT, destinationDoc.getID());
	      if (!DmsRoot.PERSONAL_ROOT.equals(dmsType) && permission.indexOf("I") == -1){
	      	request.setAttribute("odmaGetType","EML");
					request.setAttribute("result","Have no permission to Create EMAIL");
					request.setAttribute("inforCode","ERROR_EMAIL_01");        
					return ;
	      }
			
			InputStream inputStream = null;
			FormFile formFile = null;
			actionForm.getFormFieldXmlFile();
			formFile = actionForm.getUploadFile();
			inputStream = formFile.getInputStream();

			EmailReceiver mailReceiver = null;
			EmailMessageImpl emlEmailMessage = null;
			String mailServerType = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_AUTO_TRACKER_MAIL_SERVERTYPE);
			mailReceiver = EmailReceiverFactory.getEmailReceiverInstanceByServerType(sessionContainer, mailServerType);
			Session mailSession = Session.getDefaultInstance(System.getProperties(),null);
			MimeMessage msg = new MimeMessage(mailSession, inputStream);
			
			emlEmailMessage = mailReceiver.analysemailEmailMessage(msg);
			
      //create the temporarily fils
      long currentTime = new java.util.Date().getTime();
      Double randomNum = new Double((Math.random() * 1000));
      String folderName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_CACHEFOLDER_PATH);
      File catcheFolder = new File(folderName);
      if (!catcheFolder.exists()) {
        catcheFolder.mkdir();
      }
      String fileName = sessionContainer.getUserRecordID() + "_"+ currentTime + "_" + randomNum.intValue() + ".eml";
      FileOutputStream objfile = new FileOutputStream(folderName + fileName);
      msg.writeTo(objfile);
      
      String name = folderName + fileName;
      File file = new File(name);
      objfile.flush();
      objfile.close();
      
      Long sizetep = new Long(file.length());

      DocumentEmailArchiveManager manager = new DocumentEmailArchiveManager(sessionContainer, conn, "");
      
      EmailAttachmentImpl emailAttachment = new EmailAttachmentImpl();
      emailAttachment.setAttachFileName(emlEmailMessage.getSubject() +".eml"); 
      emailAttachment.setCatchFileName((fileName));
      emailAttachment.setContentID("");
      emailAttachment.setFileSize(sizetep.intValue());
      emailAttachment.setIsOrigEmail(true);
      emlEmailMessage = manager.disposeSubject(sessionContainer,conn,emlEmailMessage,actionForm.getRootID(),actionForm.getParentID());//barbin 2006-4-18
      emlEmailMessage.addAttachment(emailAttachment);			
			

			manager.saveWholeEmail(emlEmailMessage, actionForm.getRootID(),actionForm.getParentID());			 
			conn.commit();
			
			//add email audit trail record
			DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
			DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,conn);
			dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_INBOUND);
			dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EMAIL_JOURNALING);
			dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
			dmsEmailAuditTrail.setEmailFrom(emlEmailMessage.getSender());
			dmsEmailAuditTrail.setEmailTo(emlEmailMessage.getTo().replaceAll(";"," : "));
			dmsEmailAuditTrail.setEmailCc(emlEmailMessage.getCc().replaceAll(";"," : "));
			dmsEmailAuditTrail.setEmailBcc("");
			dmsEmailAuditTrail.setEmailSubject(emlEmailMessage.getSubject());
			dmsEmailAuditTrail.setSentDate(TextUtility.getDBDateTimeFormat().format(emlEmailMessage.getSendDate()));
			Iterator ite = emlEmailMessage.getAttachments().iterator();
			StringBuffer sb = new StringBuffer();
			List attchList = new ArrayList();
			while(ite.hasNext()){
				EmailAttachmentImpl attch = (EmailAttachmentImpl)ite.next();
				String attchName = attch.getAttachFileName()+" ; ";
				sb.append(attchName);
				attchList.add(attchName);
			}
			dmsEmailAuditTrail.setAttchName(sb.toString());
			dmsEmailAuditTrail.setAttchCount(new Integer(attchList.size()));
			dmsEmailAuditTrail.setAttchSource("DMS");
			dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
	    dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
	    dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
	    dmsEmailAuditTrail.setUpdateCount(new Integer(0));
	    dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
	    dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
			dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
			conn.commit();
			//end
			
			request.setAttribute("odmaGetType","EML");
			request.setAttribute("result","NEW EMAIL SUCCESS");
			request.setAttribute("inforCode","MESSAGE_NEW_EMAIL_01");
		} catch (Exception e) {
      log.error(e, e);
		}
	}
  
  public void insertMailForNotes(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
	    SessionContainer sessionContainer = this.getSessionContainer(request);
		Connection conn = this.getConnection(request);
		MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;
  		DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
  		List failReturnInfo = new ArrayList(); 
		
		try {
		
            InputStream inputStream = null;
            String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_LOTUS_SHARE_FOLDER);
            String trueFileName = actionForm.getTrueFileName();
            File files;
            InputStream newInputStream;
            InputSource input = new InputSource(); 
            try{
                files = new File(path+trueFileName);
                inputStream = new FileInputStream(files);
                newInputStream = new FileInputStream(files);
                input.setByteStream(inputStream);
            }catch(Exception e){
            	failReturnInfo.add("not found the file:"+trueFileName);
            	StringBuffer failInfo = new StringBuffer();
    			Iterator iter = failReturnInfo.iterator();
    			while(iter.hasNext()){
    				failInfo.append(iter.next().toString());
    			}
    			request.setAttribute("odmaGetType","LOTUSEMAILARCHIVE");
    			request.setAttribute("result","FAILED");
    			request.setAttribute("inforCode",failInfo.toString());
            }
			//request.getInputStream();
            
//          Create an Document node as the root for the output.
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            org.w3c.dom.Document indexFile = null;           
            EmailMessageImpl emlEmailMessage = EmailMessageImpl.newInstance();
            NodeList doclist;
            
            String  emailID="";
            String  emailSubject="";
            String  emailSender="";
            String  emailTo="";
            String  emailSendDate="";
            String  emailCC="";
            String  emailSize="";
            String  emailIsTextOly="";
            String  emailBody="";
            String  originalEmailXmlName="";
                  
            //get the email attributer
            try{
            	indexFile = docBuilder.parse(input);
            	doclist = indexFile.getElementsByTagName("Text");
    			for(int j = 0; j<doclist.getLength();j++ ){
	                Node docNode = doclist.item(j);
	                Node parentNode = docNode.getParentNode();
	                if (docNode != null && docNode.getFirstChild()!=null && parentNode != null) {
	                  if(docNode!=null&&"MessageID".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailID =((docNode.getFirstChild())).getNodeValue();
	                  }
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"Subject".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailSubject =((docNode.getFirstChild())).getNodeValue();                
	                  }
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"From".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailSender =((docNode.getFirstChild())).getNodeValue();
	                  }
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"To".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailTo =((docNode.getFirstChild())).getNodeValue();
	                  }
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"DeliveredDate".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailSendDate =((docNode.getFirstChild())).getNodeValue();
	                  }
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"CC".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailCC =((docNode.getFirstChild())).getNodeValue();
	                  }
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"odmaProcess".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailIsTextOly =((docNode.getFirstChild())).getNodeValue();
	                  }
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"Body".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailBody =((docNode.getFirstChild())).getNodeValue();
	                  } 
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"Size".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    emailSize =((docNode.getFirstChild())).getNodeValue();
	                  }               
	                  if(docNode!=null && docNode.getFirstChild()!=null&&"MailDetailFile".equals(((Element)parentNode).getAttributeNode("name").getValue())){
	                    originalEmailXmlName =((docNode.getFirstChild())).getNodeValue();
	                  }
	                }           
	              }  
    			if(emailSubject.length() ==0){
	                emailSubject = "Not Subject";
	              }
	              
	           
	              emlEmailMessage.setMessageID(emailID);
	              emlEmailMessage.setSubject(emailSubject);
	              emlEmailMessage.setSender(emailSender);
	              if (emailSendDate != null && emailSendDate !="") {
	                try{
	                	java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(SystemParameterFactory.getSystemParameter(
	  	                      SystemParameterConstant.DB_DATETIME_FORMAT),
	  	                      new Locale(SystemParameterFactory.getSystemParameter(
	  	                          SystemParameterConstant.LOCALE)));
	  	                  java.util.Date date = formatter.parse(emailSendDate);
	  	                  emlEmailMessage.setSendDate(date);
	                }catch(Exception e){
	                	failReturnInfo.add("the date format error");
	                	StringBuffer failInfo = new StringBuffer();
	        			Iterator iter = failReturnInfo.iterator();
	        			while(iter.hasNext()){
	        				failInfo.append(iter.next().toString());
	        			}
	        			request.setAttribute("odmaGetType","LOTUSEMAILARCHIVE");
	        			request.setAttribute("result","FAILED");
	        			request.setAttribute("inforCode",failInfo.toString());
	                }
	              }          
	              emlEmailMessage.setTo(TextUtility.noNull(emailTo));
	              emlEmailMessage.setCc(TextUtility.noNull(emailCC));
	              emlEmailMessage.setSize(TextUtility.parseInteger(emailSize));
	              emlEmailMessage.setIsTextOnly(false);   
	              emlEmailMessage.setContent(emailBody);
	              emlEmailMessage.setOriContent(emailBody);
	              emlEmailMessage.setOriSubject(emailSubject);
	                  
	                emlEmailMessage.setAnalyzed(true);
	                NodeList positionList = indexFile.getElementsByTagName("PositionItem");
	                Node positionNode = positionList.item(0);
	                String parentID="";
	                String rootID="";
	                String ID="";
	                if( positionNode != null){
	                	try { parentID = ((Element)positionNode).getAttribute("ParentId"); } catch (Exception ignore) {failReturnInfo.add("parentID is Null");}
		                try { rootID = ((Element)positionNode).getAttribute("RootId"); } catch (Exception ignore) {failReturnInfo.add("rootId is Null");}
			            try { ID = ((Element)positionNode).getAttribute("Id"); } catch (Exception ignore) {failReturnInfo.add("Id is Null");}
			        }
	                Integer destinationID = TextUtility.parseIntegerObj(ID);
	    			       DmsDocument destinationDoc = docRetrievalManager.getDocument(destinationID);
	                DocumentEmailArchiveManager manager = new DocumentEmailArchiveManager(sessionContainer, conn, "");
	                emlEmailMessage = manager.disposeSubject(sessionContainer,conn,emlEmailMessage,rootID,ID);
	                DmsDocument newDocument = manager.saveMailContent(emlEmailMessage,rootID,ID);
//	                add original Email Xml as attachement to dms
	                EmailAttachmentImpl emailAttachment = putAttachToCatchFile(originalEmailXmlName,emailSubject+".dxl",-1,sessionContainer);
	                emailAttachment.setIsOrigEmail(true);
	                   
	                emlEmailMessage.addAttachment(emailAttachment);
	                emlEmailMessage.setHaveAttachment(true);                
	                
	                // add attachement file to dms
	                NodeList attachmentList = indexFile.getElementsByTagName("AttachmentItem");
	                for(int j = 0; j<attachmentList.getLength();j++ ){
	                  Node docNode = attachmentList.item(j);
	                  String attachementFilePath="";
	                  if (docNode != null ) {  
	                    trueFileName = ((Element)docNode).getAttributeNode("Originalfilename").getValue();
	                    attachementFilePath = ((Element)docNode).getAttributeNode("Filename").getValue();
	                    emlEmailMessage.addAttachment(putAttachToCatchFile(attachementFilePath,trueFileName,j,sessionContainer));
	                  }
	                }
	                manager.saveAttachments(emlEmailMessage, newDocument, rootID,ID); 
	                conn.commit();
	                File sourceDirectory = new File(path);
	                File deleteFiles[] = sourceDirectory.listFiles();
	                for(int i=0; i<deleteFiles.length; i++){
	                	deleteFiles[i].delete();
	                }
	                inputStream.close() ;
	                inputStream=null;
	                
	                request.setAttribute("odmaGetType","LOTUSEMAILARCHIVE");
	    			request.setAttribute("result","SUCCESS");
	    			request.setAttribute("inforCode","MESSAGE_NEW_EMAIL_SUCCESS");

            }catch(Exception e){
            	failReturnInfo.add("Notes server make xml file error");
            	StringBuffer failInfo = new StringBuffer();
    			Iterator iter = failReturnInfo.iterator();
    			while(iter.hasNext()){
    				failInfo.append(iter.next().toString());
    			}
    			request.setAttribute("odmaGetType","LOTUSEMAILARCHIVE");
    			request.setAttribute("result","FAILED");
    			request.setAttribute("inforCode",failInfo.toString());
            }
			      
		}catch (Exception e) {
			StringBuffer failInfo = new StringBuffer();
			Iterator iter = failReturnInfo.iterator();
			while(iter.hasNext()){
				failInfo.append(iter.next().toString());
			}
			request.setAttribute("odmaGetType","LOTUSEMAILARCHIVE");
			request.setAttribute("result","FAILED");
			request.setAttribute("inforCode",failInfo.toString());
      log.error(e, e);
		}
	}
  
  /*****************************************************************************
	 * function: parse zip file . then find the same file name but except file
	 * ext. 1: pasre zip file. 2: find xml file and pasre it . get email
	 * information set in EmailMessageImpl 3: createDocument whit email body. 4
	 * save attchment to DMS 5 . make return information to lutos author: barbin
	 * 2006-9-6
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @throws ApplicationException
	 */
	public void insertMailNotesForPost(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
		SessionContainer sessionContainer = this.getSessionContainer(request);
		Connection conn = this.getConnection(request);
		MaintDmsDocumentForm actionForm = (MaintDmsDocumentForm) form;
		DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
		// defination error message return to lutos
		List failReturnInfo = new ArrayList();
		File file = null;
		InputStream inputStream = null;
		List deleteFiles = new ArrayList();
		try {
			InputSource input = new InputSource();
			String path = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_CACHEFOLDER_PATH);
			String baseDir = path + "/" + actionForm.getTrueFileName();
			String xmlName = actionForm.getTrueFileName().substring(0, actionForm.getTrueFileName().indexOf("."));
			xmlName = xmlName + ".xml";
			file = new File(baseDir);
			if (!file.exists()) {
				log.debug("the zip file not found");
			}
			// 1:
			ZipFile zipFile = new ZipFile(file);
			Enumeration e = zipFile.entries();
			while (e.hasMoreElements()) {
				ZipEntry zipEntry = (ZipEntry) e.nextElement();
				if (zipEntry.getName().equals(xmlName)) {
					inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry));
				}
			}
			if (inputStream != null) {
				try{
//				 2:
					input.setByteStream(inputStream);
					// Create an Document node as the root for the output.
					DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
					DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
					org.w3c.dom.Document indexFile = null;
					EmailMessageImpl emlEmailMessage = EmailMessageImpl.newInstance();
					NodeList doclist;

					String emailID = "";
					String emailSubject = "";
					String emailSender = "";
					String emailTo = "";
					String emailSendDate = "";
					String emailCC = "";
					String emailSize = "";
					String emailIsTextOly = "";
					String emailBody = "";
					String originalEmailXmlName = "";

					// get the email attributer

					indexFile = docBuilder.parse(input);
					doclist = indexFile.getElementsByTagName("Text");
					for (int j = 0; j < doclist.getLength(); j++) {
						Node docNode = doclist.item(j);
						Node parentNode = docNode.getParentNode();
						if (docNode != null && docNode.getFirstChild() != null && parentNode != null) {
							if (docNode != null && "MessageID".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailID = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "Subject".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailSubject = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "From".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailSender = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "To".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailTo = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "DeliveredDate".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailSendDate = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "CC".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailCC = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "odmaProcess".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailIsTextOly = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "Body".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailBody = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "Size".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								emailSize = ((docNode.getFirstChild())).getNodeValue();
							}
							if (docNode != null && docNode.getFirstChild() != null && "MailDetailFile".equals(((Element) parentNode).getAttributeNode("name").getValue())) {
								originalEmailXmlName = ((docNode.getFirstChild())).getNodeValue();
							}
						}
					}
					if (emailSubject.length() == 0) {
						emailSubject = "Not Subject";
					}

					// 3: set value in to emlEmailMessage
					emlEmailMessage.setMessageID(emailID);
					emlEmailMessage.setSubject(emailSubject);
					emlEmailMessage.setSender(emailSender);
					if (emailSendDate != null && emailSendDate != "") {
						java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT), new Locale(SystemParameterFactory.getSystemParameter(SystemParameterConstant.LOCALE)));
						java.util.Date date = formatter.parse(emailSendDate);
						emlEmailMessage.setSendDate(date);

					}
					emlEmailMessage.setTo(TextUtility.noNull(emailTo));
					emlEmailMessage.setCc(TextUtility.noNull(emailCC));
					emlEmailMessage.setSize(TextUtility.parseInteger(emailSize));
					emlEmailMessage.setIsTextOnly(false);
					emlEmailMessage.setContent(emailBody);
					emlEmailMessage.setOriContent(emailBody);
					emlEmailMessage.setOriSubject(emailSubject);

					emlEmailMessage.setAnalyzed(true);
					NodeList positionList = indexFile.getElementsByTagName("PositionItem");
					Node positionNode = positionList.item(0);
					String parentID = "";
					String rootID = "";
					String ID = "";
					if (positionNode != null) {
						try {
							parentID = ((Element) positionNode).getAttribute("ParentId");
						} catch (Exception ignore) {
							failReturnInfo.add("parentID is Null");
						}
						try {
							rootID = ((Element) positionNode).getAttribute("RootId");
						} catch (Exception ignore) {
							failReturnInfo.add("rootId is Null");
						}
						try {
							ID = ((Element) positionNode).getAttribute("Id");
						} catch (Exception ignore) {
							failReturnInfo.add("Id is Null");
						}
					}
					Integer destinationID = TextUtility.parseIntegerObj(ID);
					DmsDocument destinationDoc = docRetrievalManager.getDocument(destinationID);
					DocumentEmailArchiveManager manager = new DocumentEmailArchiveManager(sessionContainer, conn, "");
					emlEmailMessage = manager.disposeSubject(sessionContainer, conn, emlEmailMessage, rootID, ID);
					// 4: create document
					DmsDocument newDocument = manager.saveMailContent(emlEmailMessage, rootID, ID);
					emlEmailMessage.setHaveAttachment(true);
					Enumeration en = zipFile.entries();
					List attchList = new ArrayList();
					
					// 5: parse email attchment
					while (en.hasMoreElements()) {
						ZipEntry zEntry = (ZipEntry) en.nextElement();
						if (!zEntry.getName().equals(xmlName)) {
							attchList.add(zEntry.getName());
						  InputStream	is = zipFile.getInputStream(zEntry);
							OutputStream fos = new FileOutputStream(path+"/"+zEntry.getName());
							try{
								byte [] buff = new byte[1024];
								int readLen = 0;
								while((readLen = is.read(buff))!= -1){
									fos.write(buff,0,readLen);
								}
							}catch(Exception exce){
                log.error(exce, exce);
							}finally{
								is.close();
								fos.close();
							}
							File attchFile = new File(path+zEntry.getName());
							EmailAttachmentImpl emailAttachment = putAttachToCatch(path+"/"+zEntry.getName(), zEntry.getName(), -1, sessionContainer);
							emailAttachment.setIsOrigEmail(true);
							emlEmailMessage.addAttachment(emailAttachment);
							deleteFiles.add(path+"/"+zEntry.getName());
						}
					}
					manager.saveAttachments(emlEmailMessage, newDocument, rootID, ID);
					conn.commit();
					
					//add email audit trail record
					DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
					DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionContainer,conn);
					dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_INBOUND);
					dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EMAIL_JOURNALING);
					dmsEmailAuditTrail.setUserid(sessionContainer.getUserRecordID());
					dmsEmailAuditTrail.setEmailFrom(emailSender);
					dmsEmailAuditTrail.setEmailTo(emailTo.replaceAll(";"," ; "));
					dmsEmailAuditTrail.setEmailCc(emailCC.replaceAll(";"," ; "));
					dmsEmailAuditTrail.setEmailBcc("");
					dmsEmailAuditTrail.setEmailSubject(emailSubject);
					dmsEmailAuditTrail.setSentDate(TextUtility.getDBDateTimeFormat().format(emlEmailMessage.getSendDate()));
					Iterator ite = attchList.iterator();
					StringBuffer sb = new StringBuffer();
					
					while(ite.hasNext()){
						String attchName  = (String)ite.next()+" ; ";
						sb.append(attchName);
					}
					dmsEmailAuditTrail.setAttchName(sb.toString());
					dmsEmailAuditTrail.setAttchCount(new Integer(attchList.size()));
					dmsEmailAuditTrail.setAttchSource("DMS");
					dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
				  dmsEmailAuditTrail.setCreatorID(sessionContainer.getUserRecordID());
				  dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
				  dmsEmailAuditTrail.setUpdateCount(new Integer(0));
				  dmsEmailAuditTrail.setUpdaterID(sessionContainer.getUserRecordID());
				  dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
					dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
					conn.commit();

					request.setAttribute("odmaGetType", "LOTUSEMAILARCHIVE");
					request.setAttribute("result", "SUCCESS");
					request.setAttribute("inforCode", "MESSAGE_NEW_EMAIL_SUCCESS");
				}catch(Exception ex){
          log.error(ex, ex);
					failReturnInfo.add("save error!");
				}finally{
					if(zipFile != null){zipFile.close() ;}
					if(inputStream != null){inputStream.close();}
				}
			} else {
				failReturnInfo.add("post error from lotus");
				StringBuffer failInfo = new StringBuffer();
				Iterator iter = failReturnInfo.iterator();
				while (iter.hasNext()) {
					failInfo.append(iter.next().toString());
				}
				request.setAttribute("odmaGetType", "LOTUSEMAILARCHIVE");
				request.setAttribute("result", "FAILED");
				request.setAttribute("inforCode", failInfo.toString());
			}

		} catch (Exception e) {
      log.error(e, e);
			StringBuffer failInfo = new StringBuffer();
			Iterator iter = failReturnInfo.iterator();
			while (iter.hasNext()) {
				failInfo.append(iter.next().toString());
			}
			request.setAttribute("odmaGetType", "LOTUSEMAILARCHIVE");
			request.setAttribute("result", "FAILED");
			request.setAttribute("inforCode", failInfo.toString());
		} finally {
			try {
				file.delete();
				Iterator iter = deleteFiles.iterator();
				while(iter.hasNext()){
					String filePath =  (String)iter.next();
					File deleteFile = new File(filePath);
					deleteFile.delete();
				}
			}catch(Exception ignore){}
		}
	}

  /**
   * allowGetList
   *
   * @return  The if allow get the list.
   */  
  public boolean allowGetList(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer,conn);
    UpdateAlertDAObject updateAlertDAO = new UpdateAlertDAObject(sessionContainer,conn);
    UpdateAlertTypeDAObject updateAlertTypeDAO = new UpdateAlertTypeDAObject(sessionContainer,conn);
    
    boolean allowGetList = false;

    Integer id = TextUtility.parseIntegerObj(form.getID());
    
    // if document had been deleted from recycle bin, the document can't be view. (lee.lv 2006/10/20 EIP-342)
    DmsDocument dmsDocument = (DmsDocument)dmsDocumentDAO.getObjectByID(id);
    if (dmsDocument== null) {
      this.addError(request, "errors.dms.check.document_been_deleted");
      return false;
    }
    
    Integer updateAlertID = TextUtility.parseIntegerObj(request.getParameter("updateAlertID"));
    Integer updateAlertSystemLogID = TextUtility.parseIntegerObj(request.getParameter("updateAlertSystemLogID"));
    Integer tmpUpdateAlertID = updateAlertDAO.getInvitationIDByAlertIDorSystemLogID(updateAlertID, updateAlertSystemLogID);
    //if tmpUpdateAlertID is not null, then it is from a invitation.
    boolean isInvitation = (tmpUpdateAlertID!=null);
    
    if (isInvitation) {
      //lee.lv edit for bug eip-106 in 06/08/23 start...
      MtmUpdateAlertRecipientDAObject mtmUpdateAlertRecipientDAObject= new MtmUpdateAlertRecipientDAObject(sessionContainer,conn);
      List invitations = mtmUpdateAlertRecipientDAObject.getInvitationList(id, tmpUpdateAlertID, sessionContainer.getUserRecordID(), permissionManager.getUserRoles(), permissionManager.getUserGroups());
      if (invitations.isEmpty()) {
        this.addError(request, "errors.dms.invitation.fail.canced");
      }else {
        String errorMessage = null;
        for (int i=0; i<invitations.size(); i++) {
          MtmUpdateAlertRecipient recipient = (MtmUpdateAlertRecipient)invitations.get(i);
          UpdateAlertType updateAlertType = null;
          try {
            updateAlertType = (UpdateAlertType)updateAlertTypeDAO.getObjectByID(recipient.getUpdateAlertTypeID());
          }catch (Exception ex) {
            errorMessage = "errors.dms.invitation.fail.canced";
          }
          if (updateAlertType==null) {
            errorMessage = "errors.dms.invitation.fail.canced";
          }else {
            Timestamp dueDate = updateAlertType.getDueDate();
            if (dueDate!=null && System.currentTimeMillis()-dueDate.getTime()>86400000) {
              errorMessage = "errors.dms.invitation.fail.expired";
            }else {
              allowGetList = true;
              break;
            }
          }
        }
        if (!allowGetList) {
          this.addError(request, errorMessage);
        }
      }
    }else {
      boolean hasRight = permissionManager.hasAccessRight(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, id, "R");
      if (!hasRight) {
        this.addError(request, "errors.dms.alert.fail.noright");
      }else {
        allowGetList = true;
      }
    }
    return allowGetList;
  }

  protected String getApplicationBaseURL(){
    return SystemParameterFactory.getSystemParameter(SystemParameterConstant.APPLICATION_BASE_URL);
  }  
  
  private EmailAttachmentImpl putAttachToCatchFile(String attachFilePath,String truFileName, int sequence,SessionContainer sessionContainer) {
	    EmailAttachmentImpl emailAttachment = new EmailAttachmentImpl();
	    String lotusEmailDir = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_LOTUS_SHARE_FOLDER);
	    try {
	      File attachFile = new File(lotusEmailDir+attachFilePath);
	      if(attachFile.exists()){
	        long currentTime = new java.util.Date().getTime();
	        Random rand = new Random();
	        Double randomNum = new Double((Math.random() * 1000));
	        String folderName = SystemParameterFactory
	        .getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_CACHEFOLDER_PATH);
	        File catcheFolder = new File(folderName);
	        if (!catcheFolder.exists()) {
	          catcheFolder.mkdir();
	        }
	        String fileName = sessionContainer.getUserRecordID() + "_"
	        + currentTime + "_" + randomNum.intValue() + "_" + sequence
	        + ".tmp";
	        FileOutputStream objfile = new FileOutputStream(folderName
	            + fileName);
	        InputStream inputStream =  new FileInputStream(attachFile);
	        int bufferSize = 8192;
	        byte[] buffer = new byte[bufferSize];
	        int length = -1;
	        int allLength = 0;
	        while ((length = inputStream.read(buffer, 0, bufferSize)) != -1) {
	          objfile.write(buffer, 0, length);
	        }
	        inputStream.close();
	        inputStream = null;
	        objfile.flush();
	        objfile.close();
	        emailAttachment.setAttachFileName(decodeText(truFileName));
	        emailAttachment.setCatchFileName((fileName));
	        emailAttachment.setContentID(null);
	        emailAttachment.setFileSize((int)attachFile.length());
	       
	      }
	    } catch (Exception e) {
        log.error(e, e);
	    }
	    return emailAttachment;
	  }
  
  /******************************
   * 
   * @param attachFilePath
   * @param truFileName
   * @param sequence
   * @param sessionContainer
   * @return
   */
  	
  	private EmailAttachmentImpl putAttachToCatch(String attachFilePath, String truFileName, int sequence, SessionContainer sessionContainer) {
  		EmailAttachmentImpl emailAttachment = new EmailAttachmentImpl();
  	//	String lotusEmailDir = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_LOTUS_SHARE_FOLDER);
  		try {
  			File attachFile = new File(attachFilePath);
  			if (attachFile.exists()) {
  				long currentTime = new java.util.Date().getTime();
  				Random rand = new Random();
  				Double randomNum = new Double((Math.random() * 1000));
  				String folderName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_CACHEFOLDER_PATH);
  				File catcheFolder = new File(folderName);
  				if (!catcheFolder.exists()) {
  					catcheFolder.mkdir();
  				}
  				String fileName = sessionContainer.getUserRecordID() + "_" + currentTime + "_" + randomNum.intValue() + "_" + sequence + ".tmp";
  				FileOutputStream objfile = new FileOutputStream(folderName + fileName);
  				InputStream inputStream = new FileInputStream(attachFile);
  				int bufferSize = 8192;
  				byte[] buffer = new byte[bufferSize];
  				int length = -1;
  				int allLength = 0;
  				while ((length = inputStream.read(buffer, 0, bufferSize)) != -1) {
  					objfile.write(buffer, 0, length);
  				}
  				inputStream.close();
  				inputStream = null;
  				objfile.flush();
  				objfile.close();
  				emailAttachment.setAttachFileName(decodeText(truFileName));
  				emailAttachment.setCatchFileName((fileName));
  				emailAttachment.setContentID(null);
  				emailAttachment.setFileSize((int) attachFile.length());

  			}
  		} catch (Exception e) {
        log.error(e, e);
  		}
  		return emailAttachment;
  	}
  
  /**
   * Method  decodeText
   * @param str
   * @return
   */
  public String decodeText(String str){
    if(str == null ){
      return "";
    }  
    if ( str.indexOf("=?x-unknown?") >=0 ){
      str = str.replaceAll("x-unknown","gbk"  );
    }
    try{
      str = MimeUtility.decodeText( str ); 
    }catch( Exception e1){
      return str ;
    }    
    return str;
  }
  
  /**
   * resolve the problem duplicate name
   * EIP-438 06/12/29 LEE 
   * @param request
   */
  public void regeditDuplicateNameCache(HttpServletRequest request) {
    ApplicationContainer application = this.getSessionContainer(request).getAppContainer();
    if (application!=null) {
      application.regeditDuplicateNameCache();
    }
  }
  
  /**
   * resolve the problem duplicate name
   * EIP-438 06/12/29 LEE 
   * @param request
   */
  public void unlockDuplicateNameCache(HttpServletRequest request) {
    ApplicationContainer application = this.getSessionContainer(request).getAppContainer();
    if (application!=null) {
      application.unlockDuplicateNameCache();
    }
  }
}
